1

I'm trying to create a simple calculation, the user enters in a value "kWh" and it'll output "ChargeAmount"

However, I am having problems with converting the ChargeAmount into a decimal value and I am getting the error "Input string was not in the correct format".I can manually change the value for ChargeAmount in the debugger, and continue the program, which will output the ChargeAmount correctly. So I think the error is associated with the decimal conversion.

Is there something in the code that I did wrong?

Thank you!

private decimal CCustMethod()
    {
        decimal kWh = Convert.ToDecimal(txtkWh.Text);
        decimal ChargeAmount = Convert.ToDecimal(txtChargeAmount.Text);
        if (radCommercial.Checked) //User checks on Commercial
        {
            if (kWh < 1000m) //Calculation for first 1000 kWh used 
            {
                ChargeAmount = 60.0m;
            }

            else//Calculation when over 1000 kWh usage 
            {
                ChargeAmount = (kWh - 1000) * 0.045m + 60.0m;
            }

        }
        txtChargeAmount.Text = string.Format("{0:C2}", ChargeAmount); //Convert Flat Rate into format
        return ChargeAmount;
    }
AU-Gold
  • 11
  • 3
  • 1
    What do you type in the txtkWh box? There are thousands of question about this and all boils down to a simple fact. The input you give is not convertible to a decimal (or integer, float, datetime etc...) according to the localization rules of your operating system – Steve Jan 08 '17 at 23:06
  • I type in any decimal value so "5.6" as an example – AU-Gold Jan 08 '17 at 23:08
  • 1
    And this is not convertible to a decimal if you live in a country that uses something different as separator between integer and decimal part of a number – Steve Jan 08 '17 at 23:08
  • 2
    Possible duplicate of [Problem parsing currency text to decimal type](http://stackoverflow.com/questions/4953037/problem-parsing-currency-text-to-decimal-type) – Slai Jan 08 '17 at 23:15
  • Thanks so much! it was the $ that was causing the value to not be able to converted – AU-Gold Jan 08 '17 at 23:37
  • @AU-Gold If you need to support $ in currency field you can do something like decimal result = decimal.Parse("$22.04",NumberStyles.Currency); . NumberStyles is in System.Globalization namespace. – Hakunamatata Jan 09 '17 at 00:06

1 Answers1

0

You could try something like this :

System.Globalization.CultureInfo customCulture = (System.Globalization.CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
customCulture.NumberFormat.NumberDecimalSeparator = ".";

System.Threading.Thread.CurrentThread.CurrentCulture = customCulture;

Or something like this :

using System.Globalization;
CultureInfo culture = new CultureInfo("en-US");
Convert.ToDecimal(value, culture);

So in your case it could just be :

decimal ChargeAmount = Convert.ToDecimal(txtChargeAmount.Text,new CultureInfo("en-US"));
Dimitris Sapikas
  • 622
  • 1
  • 6
  • 22