I've been getting this error whenever I run the application.
System.FormatException: 'Input string was not in a correct format.' on the decimal weight = Convert.ToDecimal(txtboxWeight.Text);
I don't know where I went wrong in this part this code is running from my different program.
private void ShowtotalPayment()
{
decimal weight = Convert.ToDecimal(txtboxWeight.Text);
decimal price = Convert.ToDecimal(lblPrice.Text);
int quantity = Convert.ToInt32(NumQuantity.Text);
decimal totalPayment = weight * price * quantity;
lblTotalPayment.Text = totalPayment.ToString();
};
For example, change:
decimal weight = Convert.ToDecimal(txtboxWeight.Text);
To:
decimal weight;
if (Decimal.TryParse(txtboxWeight.Text, out weight)) {
// ... do something with "weight" or proceed in here ...
}
else {
MessageBox.Show("Invalid Decimal in Weight!");
}
Related
I am having an issue with rounding on a c# Payroll program.
I tested it with 15.50 hourly rate x 39.75 hours. This comes to $616.125 gross pay, rounded up to $616.13 gross.
Then I did a fixed Income tax of 25%, which means the final Net Pay of (15.50 x 39.75) x .25 = 462.10
However it keeps displaying a Net Pay of 462.09, so it must not be using the rounded gross pay for the display part. The Gross Pay and Income tax are displaying correctly
Here is all of the code, my guess is that this line needs to be changed among others:
decimal incomeTax = Math.Round(grossPay, 3) * taxRate;
Any ideas what I need to do to get it to round correctly?
decimal hourlyRate = 0;
decimal hoursWorked = 0;
decimal grossPay = 0m;
decimal incomeTax = 0m;
decimal netPay = 0m;
decimal taxRate = .25m;
private void btnCalculate_Click(object sender, EventArgs e)
{
decimal hourlyRate = Convert.ToDecimal(txtHourlyRate.Text);
decimal hoursWorked = Convert.ToDecimal(txtHoursWorked.Text);
decimal grossPay = Math.Round(hourlyRate * hoursWorked, 3);
decimal incomeTax = Math.Round(grossPay, 3) * taxRate;
decimal netPay = grossPay - incomeTax;
txtGrossPay.Text = grossPay.ToString("c");
txtIncomeTax.Text = incomeTax.ToString("c");
txtNetPay.Text = netPay.ToString("c");
}
private void btnClear_Click(object sender, EventArgs e)
{
hourlyRate = 0;
hoursWorked = 0;
grossPay = 0m;
incomeTax = 0m;
netPay = 0m;
txtHourlyRate.Text = "";
txtHoursWorked.Text = "";
txtGrossPay.Text = "";
txtIncomeTax.Text = "";
txtNetPay.Text = "";
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
616.125 undergoes midpoint rounding. decimal uses banker's rounding by default. So (and this is something you can check yourself very easily if you just step through your code):
Math.Round(616.125M, 2) // 616.12M
Of course, you're also rounding to three decimal places, so you're actually getting 616.125M instead of 616.12M (or 616.13M) anyway.
You're doing something quite dangerous - you're guessing around tax calculations. Don't do that. Find the applicable tax laws - they will have the exact method used for calculating taxes. Follow those to a T. They specify where and when and how you should round anything. Most likely, all rounding (except for the final price/tax) is supposed to be done to four decimal places, not two, but again, don't guess - read the laws, and make sure you understand them perfectly.
decimal grossPay = Math.Round(hourlyRate * hoursWorked, 3);
returns 616.125, for which the rest of the calculations correctly lead to 462.09.....
It should be
decimal grossPay = Math.Round(hourlyRate * hoursWorked, 2, MidpointRounding.AwayFromZero);
Note the second parameter, the decimal place to round to, is 2 instead of 3, and the MidpointRounding parameter which will round 616.125 to 616.13 and get the result you expect.
i have this code in my updatetobill code. im planning to round it off to nearest tenth i think? for example the price is 123456.123456, what i want to do is to have it as 123456.12 because since its a price, i need the cents. thanks in advance for any help :)
private void UpdateTotalBill()
{
double vat = 0;
double TotalPrice = 0;
long TotalProducts = 0;
foreach (DataListItem item in dlCartProducts.Items)
{
Label PriceLabel = item.FindControl("lblPrice") as Label; // get price
TextBox ProductQuantity = item.FindControl("txtProductQuantity") as TextBox; // get quantity
double ProductPrice = Convert.ToInt64(PriceLabel.Text) * Convert.ToInt64(ProductQuantity.Text); //computation fro product price. price * quantity
vat = (TotalPrice + ProductPrice) * 0.12; // computation for total price. total price + product price
TotalPrice = TotalPrice + ProductPrice+40 +vat;
TotalProducts = TotalProducts + Convert.ToInt32(ProductQuantity.Text);
}
Label1.Text = Convert.ToString(vat);
txtTotalPrice.Text = Convert.ToString(TotalPrice); // put both total price and product values and converting them to string
txtTotalProducts.Text = Convert.ToString(TotalProducts);
}
Just round it Math.Round like;
Math.Round(TotalPrice, 2) // 123456.12
Also you can use Math.Round(Double, Int32, MidpointRounding) overload to specify your MidpointRounding is AwayFromZero or ToEven. ToEven is the default option.
The best way to do this when you want to transform string is using the CurrencyFormat. You can use the code below:
txtTotalPrice.Text = TotalPrice.ToString("C");
txtTotalProducts.Text = TotalProducts.ToString("C");
Instead which:
txtTotalPrice.Text = Convert.ToString(TotalPrice);
txtTotalProducts.Text = Convert.ToString(TotalProducts);
I'm trying to make a simple calculator using radio buttons in asp.net and c#. Two numbers are entered into a textbox each and a submit button is clicked and entered into a label.
The error I get is when the radio button is checked and submit is clicked, I get a runtime error; can anyone please help diagnose why?
This is my code:
int total;
if (rbAdd.Checked)
{
total = Convert.ToInt32(tbNo1.Text) + Convert.ToInt32(tbNo2.Text);
lblAns2.Text = total.ToString();
}
if (rbMult.Checked)
{
total = Convert.ToInt32(tbNo1.Text) * Convert.ToInt32(tbNo2.Text);
lblAns2.Text = total.ToString();
}
Simplified code that still fails the same way:
int total = 0;
int no1 = Convert.ToInt32(tbNo1.Text);
int no2 = Convert.ToInt32(tbNo2.Text);
if (rbAdd.Checked)
{
total = no1 + no2;
}
else if (rbMult.Checked)
{
total = no1 * no2;
}
lblAns2.Text = total.ToString();
I've tried your code and I got error message(Input string was not in a correct format.) only whenever I enter non integer values, because of your convert code Convert.ToInt32(tbNo1.Text);.
Do you want the entered values to be only integer? If so, please try this code instead (Modified from John Saunders code):
int total = 0;
int no1 = Convert.ToInt32(Math.Round(decimal.Parse(tbNo1.Text), 0));
int no2 = Convert.ToInt32(Math.Round(decimal.Parse(tbNo2.Text), 0));
if (rbAdd.Checked)
{
total = no1 + no2;
}
else if (rbMult.Checked)
{
total = no1 * no2;
}
lblAns2.Text = total.ToString();
You also have to validate the entered values as well to protect invalid characters.
Otherwise if you don't need to convert the entered values to be integer you could use this code:
decimal total = 0;
decimal no1 = decimal.Parse(tbNo1.Text);
decimal no2 = decimal.Parse(tbNo2.Text);
if (rbAdd.Checked)
{
total = no1 + no2;
}
else if (rbMult.Checked)
{
total = no1 * no2;
}
lblAns2.Text = total.ToString();
I need to format a decimal to a minor currency e.g. 10.00 should be 1000.
decimal currency = 10.00m;
System.Console.WriteLine(currency.ToString("######"));
Produces 10, how do I get the decimal points to be added to that?
The solution is as simple as just
* 100
I would create an extension method like this that would produce always the expected result, with the required number of decimals:
public static class DecimalExtension
{
public static string FormatAsMinorCurrency(this decimal value) {
var numberFormat = (NumberFormatInfo)CultureInfo.CurrentCulture.NumberFormat.Clone();
numberFormat.CurrencyDecimalDigits = 2;
numberFormat.CurrencyDecimalSeparator = ".";
numberFormat.CurrencySymbol = "";
numberFormat.CurrencyGroupSeparator = "";
return value.ToString("c", numberFormat).Replace(".", "");
}
}
The results:
1.FormatAsMinorCurrency()
100
10.FormatAsMinorCurrency()
1000
1000000.34102350915091M.FormatAsMinorCurrency()
100000034
It's a little more complicated than that, but this is my code:
private void button1_Click(object sender, EventArgs e)
{
Decimal num1 = Convert.ToDecimal(textBox1.Text);
Decimal num2 = Convert.ToDecimal(textBox2.Text);
Decimal total = num1 + num2;
textBox3.Text = total.ToString("C");
Decimal total2 = Convert.ToDecimal(total);
total2 = total * 4.2;
textBox4.Text = Convert.ToString(total2);
Basically it's this: I have 4 text boxes, and I want to be able to put in a number in box1 and box2. Box three will multiply box 1 & 2 and convert it to currency. Box four will take Box 3s value and change it back to decimal and multiply a number. I can get it to work as long as total2 does not have a decimal. When it has one it will fail.
The program is basically a cash register program that you put in the following:
QTY (box 1)
Amonunt (box 2)
Subtotal (box 3)
Total (box 4)
Any ideas will be helpful.
Thanks,
Caleb
If I understand the problem correctly you perform operations on decimal variables holding currency values. Often it means maintaining a specific resolution (e.g 2 digits after decimal point for cents). Since Decimal is a general purpose type you need to maintain the required resolution programmatically.
example:
static Decimal RoundToCents(Decimal value)
{
return Math.Round(value, 2, MidpointRounding.AwayFromZero);
}
Decimal num1 = RoundToCents(Convert.ToDecimal(textBox1.Text));
Decimal num2 = RoundToCents(Convert.ToDecimal(textBox2.Text));
Decimal total = num1 + num2; // no rounding is needed for additions and subtractions
Decimal total2 = RoundToCents(total * 4.2m);
The fundamental problem is that you are mixing decimal and double in this line:
total2 = total * 4.2;
total is decimal and 4.2 is a double literal. To write a decimal literal use the m suffix.
total2 = total * 4.2m;