.NET: Parsing localized currency

左心房为你撑大大i 提交于 2021-02-05 02:40:38

问题


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()?


回答1:


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);
} 



回答2:


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");


来源:https://stackoverflow.com/questions/2107674/net-parsing-localized-currency

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!