Problem parsing currency text to decimal type

How about using:

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

The MSDN documentation on Decimal.Parse states:

"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


This way it works for me:

NumberFormatInfo MyNFI = new NumberFormatInfo();
MyNFI.NegativeSign = "-";
MyNFI.CurrencyDecimalSeparator = ".";
MyNFI.CurrencyGroupSeparator = ",";
MyNFI.CurrencySymbol = "$";

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

1.) You have to define the currency separator instead of the number separator. 2.) Because you defined the currency values only, you need to define the NumberStyles.Currency while parsing.


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.

Much like @MEN, I had to include NumberFormatInfo before the .Parse() method worked properly. However, specifying the decimal with CurrencyDecimalSeparator wasn't necessary for me. You'll have to include all the properties you need for your numbers. Here's a list in the class definition docs:

MSDN Docs - NumberFormatInfo Class

I'll never get negative numbers in my implementation, so I chose not to include that. Here's what I have:

string currencyAmount = "$45.00";

NumberFormatInfo FormatInfo = new NumberFormatInfo();
FormatInfo.CurrencyGroupSeparator = ",";
FormatInfo.CurrencySymbol = "$";

// Result: 45.00
decimal parsedCurrency = decimal.Parse(currencyAmount, NumberStyles.Currency, FormatInfo);