.NET:解析本地化货币

7
假设我有一个字符串,该字符串的值是一个本地化的货币金额。所谓本地化,是指该国家可能使用逗号而不是小数点等等(这只是我知道的一种本地化区别)。
我该如何将其中一个这样的字符串解析为其对应的十进制数?decimal.TryParse()会识别本地化格式吗?我如何在TryParse()中指定CultureInfo
2个回答

8
以下是使用指定的 CultureInfo(在此处为瑞典文)的 decimal.TryParse 的示例:

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

0

decimal.TryParse 有两个重载。其中一个将 CultureInfo 作为参数(CultureInfo 实现 IFormatProvider):

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

另一个函数需要较少的参数,并使用系统的CultureInfo:
System.Decimal.TryParse(string s, out decimal result)

我不是完全确定,但我认为您可以通过以下方式设置当前系统文化:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接