问题
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 string
s into their decimal
s 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