Hun1Ahpu
Hun1Ahpu

Reputation: 3355

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

Upvotes: 4

Views: 710

Answers (5)

Gil
Gil

Reputation: 138

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

Upvotes: 0

Pieter van Ginkel
Pieter van Ginkel

Reputation: 29632

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.

Upvotes: 4

YWE
YWE

Reputation: 2909

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

Upvotes: 1

steinar
steinar

Reputation: 9653

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.

Upvotes: 8

akonsu
akonsu

Reputation: 29536

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

Upvotes: 1

Related Questions