Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem parsing currency text to decimal type

I am trying to parse a string like "$45.59" into a decimal. For some reason I am getting exception that the input was not in the correct format. I don't care about all the localization stuff because this is not going to be a global program. Here is what I am doing. Do you see any problems?

NumberFormatInfo MyNFI = new NumberFormatInfo(); 
MyNFI.NegativeSign = "-"; 
MyNFI.NumberDecimalSeparator = "."; 
MyNFI.NumberGroupSeparator = ",";
MyNFI.CurrencySymbol = "$"; 
decimal d  = decimal.Parse("$45.00", MyNFI);    // throws exception here...
like image 669
PICyourBrain Avatar asked Feb 10 '11 03:02

PICyourBrain


2 Answers

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

like image 131
John Koerner Avatar answered Nov 14 '22 12:11

John Koerner


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.

like image 17
MEN Avatar answered Nov 14 '22 11:11

MEN