【问题标题】:Convert.ToDecimal throws exception for simple stringConvert.ToDecimal 为简单字符串引发异常
【发布时间】:2015-02-13 00:34:33
【问题描述】:

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

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

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

输入字符串的格式不正确。在 System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal) 在 System.Number.ParseDecimal(String value, NumberStyles options, NumberFormatInfo numfmt) 在 System.Convert.ToDecimal(String value) 在 Presentation .Models.OrderBaseModel.Response(FormCollection response, String responseUrl)

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

【问题讨论】:

  • 这可能是文化问题 - 您是否尝试解析“10,00”?

标签: c# string


【解决方案1】:

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

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

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

【讨论】:

  • 它仍然可以抛出,因为CreateSpecificCulture 使用控制面板中的用户覆盖,并且用户可以覆盖小数分隔符。最好改用CultureInfo.InvariantCulture
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
  • 2014-10-17
  • 1970-01-01
  • 2022-10-15
  • 2017-07-21
  • 2014-05-09
相关资源
最近更新 更多