开发者

Cannot parse double

I'm trying to parse values like $15,270.75 with the expression

double cost = 0;
开发者_如何转开发double.TryParse("$15,270.75", NumberStyles.AllowThousands | NumberStyles.AllowCurrencySymbol | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out cost);

but have no success


The currency symbol of Invariant culture is not $, its ¤. This works:

double cost = double.Parse("¤15,270.75", NumberStyles.AllowThousands | NumberStyles.AllowCurrencySymbol | NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture);

You'll need a CultureInfo that supports exactly this format.


The following works:

var culture = new CultureInfo("en-US");

culture.NumberFormat.CurrencyGroupSeparator = ".";
culture.NumberFormat.CurrencyDecimalSeparator = ",";

double.TryParse("$15.270,75", NumberStyles.AllowThousands | NumberStyles.AllowCurrencySymbol | NumberStyles.AllowDecimalPoint, culture, out cost);

The culture I used here is en-US for the $ symbol. The reason I manually set the group and decimal separators is because the format used in the input string are different from the culture of en-US.

Maybe you are expecting a specific culture that is not en-US. Try passing that one.


this is because you are using InvariantCulture. you need an american CultureInfo


This will not work with CultureInfo.Invariant culture. Use an appropriate CultureInfo.


If you want something that works for any locale, use CultureInfo.CurrentCulture for the IFormatProvider parameter.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜