Let's say I have a string
, and that strin开发者_Go百科g
'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 string
s into their decimal
s numeric equivalents? Will decimal.TryParse()
recognize localized formatting? How do I specify the CultureInfo
with TryParse()
?
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);
}
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");
精彩评论