开发者

.NET: Parsing localized currency

开发者 https://www.devze.com 2022-12-17 20:47 出处:网络
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. (Tha

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 strings into their decimals 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");
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号