Parsing Currency Strings – glitch in Microsoft’s Globalization framework (.NET 1.1 & 2.0)

I’m working on a currency localization feature in a banking application, and working through different ways to parse currency strings.  One way to do this is to call Decimal.Parse(), passing in the currency string and an instance of NumberFormatInfo, which specifies how the string is formatted.  Here’s an example:

Parsing Swiss Franks from a string to a decimal:

NumberFormatInfo infoSwissFranc = new NumberFormatInfo();
infoSwissFranc.CurrencyDecimalSeparator = “,”;
infoSwissFranc.CurrencySymbol = “SFr.”;
infoSwissFranc.CurrencyGroupSeparator = ” “;
Console.WriteLine(Decimal.Parse(“SFr. 1 111 111 110,11″, NumberStyles.Currency, infoSwissFranc).ToString());

Here’s another example that parses the Swedish Krona format:

NumberFormatInfo infoSEK = new NumberFormatInfo();
infoSEK.CurrencySymbol = “kr”;
infoSEK.CurrencyGroupSeparator = “-”;
infoSEK.CurrencyDecimalSeparator = “,”;
Console.WriteLine(Decimal.Parse(“111-111-110-11 kr”, NumberStyles.Currency, infoSEK).ToString());

Oops, the 2nd snippet doesn’t work.  In this case, assigning a value of CurrencyDecimalSeparator is not good enough.  You must also assign the same value to NumberDecimalSeparator as well, or an exception will be raised.  Apparently, this is only necessary if CurrencyGroupSeparator is a decimal (CurrencyGroupSeparator =”.”)  and the currency symbol is at the end of the string instead of the beginning.  Although setting NumberDecimalSeparator may be required when parsing when parsing numbers using NumberStyles.Number, it should not be required when NumberStyles.Currency is specified.  I could be missing something, but it looks like a glitch in the .NET framework. 

After adding NumberDecimalSeparator (in red), this code will successfully parse the Swedish Krona format:

NumberFormatInfo infoSEK = new NumberFormatInfo();
infoSEK.CurrencySymbol = “kr”;
infoSEK.CurrencyGroupSeparator = “-”;
infoSEK.CurrencyDecimalSeparator = “,”;
infoSEK.NumberDecimalSeparator = “,”;
Console.WriteLine(Decimal.Parse(“111-111-110-11 kr”, NumberStyles.Currency, infoSEK).ToString());

Leave a Reply