简体   繁体   English

C#,输入字符串格式不正确,十进制值

[英]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" 我正在尝试创建一个简单的计算,用户输入值“kWh”并输出“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. 但是,我将ChargeAmount转换为十进制值时遇到问题,我收到错误“输入字符串格式不正确”。我可以在调试器中手动更改ChargeAmount的值,然后继续执行程序,正确输出ChargeAmount。 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"));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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