tags:

views:

71

answers:

5

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

+1  A: 

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

akonsu
+7  A: 

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.

steinar
+1  A: 

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

YWE
+4  A: 

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.

Pieter
A: 

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

Gil