When I tried to run the code from @JohnKoerner, it would fail with the exception:
System.FormatException
, with the message: "Input string was not in a correct format."
. @MEN s answer was helpful, but I wanted to add some additional insight about the accepted answer and how to fix that problem.
就像@MEN一样,在.Passe()
方法正常工作之前,我必须包含NumberFormatInfo
。但是,我不需要用CurrencyDecimalSeparator
指定小数。您必须包含数字所需的所有属性。以下是类定义文档中的列表:
MSDN文档-NumberFormatInfo类
在我的实现中,我永远不会得到负数,所以我选择不包括它。以下是我所拥有的:
string currencyAmount = "$45.00";
NumberFormatInfo FormatInfo = new NumberFormatInfo();
FormatInfo.CurrencyGroupSeparator = ",";
FormatInfo.CurrencySymbol = "$";
// Result: 45.00
decimal parsedCurrency = decimal.Parse(currencyAmount, NumberStyles.Currency, FormatInfo);