简体   繁体   中英

C#, Input string was not in the correct format, decimal value

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;
    }

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"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM