Skip to main content
 首页 » 编程设计

c#之Convert.ToDecimal 为简单字符串抛出异常

2024年02月06日27bhlsheji

我正在尝试将字符串“10.00”转换为十进制,如下所示:

decimal a = Convert.ToDecimal("10.00"); 

但由于某些令人难以置信的原因,我得到了这个错误:

Input string was not in a correct format. at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal) at System.Number.ParseDecimal(String value, NumberStyles options, NumberFormatInfo numfmt) at System.Convert.ToDecimal(String value) at Presentation.Models.OrderBaseModel.Response(FormCollection response, String responseUrl)

还有更深层次的原因吗? “10.00”字符串怎么会无法解析??

请您参考如下方法:

Convert.ToDecimal() 调用 Decimal.Parse()

为确保 10.00 能够解析,您需要使用能够解析它的区域性。

var culture = CultureInfo.InvariantCulture 
decimal a = Decimal.Parse("10.00",culture);