c# - 将货币文本解析为十进制类型时出现问题

标签 c# parsing decimal number-formatting

我正在尝试将“$45.59”之类的字符串解析为小数。出于某种原因,我收到输入格式不正确的异常。我不关心所有本地化的东西,因为这不会是一个全局计划。这就是我在做什么。有什么问题吗?

NumberFormatInfo MyNFI = new NumberFormatInfo(); 
MyNFI.NegativeSign = "-"; 
MyNFI.NumberDecimalSeparator = "."; 
MyNFI.NumberGroupSeparator = ",";
MyNFI.CurrencySymbol = "$"; 
decimal d  = decimal.Parse("$45.00", MyNFI);    // throws exception here...

最佳答案

如何使用:

decimal d = decimal.Parse("$45.00", NumberStyles.Currency);

有关 Decimal.Parse 的 MSDN 文档状态:

"The s parameter is interpreted using the NumberStyles.Number style. This means that white space and thousands separators are allowed but currency symbols are not. To explicitly define the elements (such as currency symbols, thousands separators, and white space) that can be present in s, use the Decimal.Parse(String, NumberStyles, IFormatProvider) method

关于c# - 将货币文本解析为十进制类型时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4953037/

相关文章:

c# - 使用 C#/WPF 监听击键

c# - OAuth 不记名 token 身份验证未通过签名验证

c++ - Boost Spirit 调试输出不出现

python - 如何计算对话中每个角色所说的单词数并将计数存储在字典中?

ruby - 在对它进行立方根然后重新立方后,我可以保持大量的准确性吗?

c++ - 设置精度和文件

c# - 如何在 C#/WPF/XAML 中将整个对象而不只是一个属性绑定(bind)到组合框列表的控件?

c# - 如何消除特定字符串后面的数字

python - 如何处理没有结尾斜杠的空 HTML 元素?

python - 在 python-2.6 : how to do it and why they didn't do it 中从 float 转换为十进制