views:

212

answers:

2

Let's say I have a string, and that string's value is an amount of money, localized. By localized, I mean that if the country may use commas instead of decimal points, for example. (That's just one localization difference I know if.)

How can I parse one of these strings into their decimals numeric equivalents? Will decimal.TryParse() recognize localized formatting? How do I specify the CultureInfo with TryParse()?

+4  A: 

Here is an example of decimal.TryParse with a specified CultureInfo (Swedish in this case):

string s = "10,95";
decimal d;
if (decimal.TryParse(s, NumberStyles.Number, CultureInfo.GetCultureInfo("sv-SE"),out d))
{
    Console.WriteLine(d);
} 
Fredrik Mörk
A: 

The decimal.TryParse comes with 2 overloads. One of them takes the culture info as argument (the CultureInfo implements IFormatProvider):

System.Decimal.TryParse(string s, System.Globalization.NumberStyles style, System.IFormatProvider provider, out decimal result)

The other one takes much less arguments and uses the systems CultureInfo:

System.Decimal.TryParse(string s, out decimal result)

I'm not completly sure, but I think you could set the current system culture by:

Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("sv-SE");
Emil