Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot parse double

Tags:

c#

parsing

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

like image 320
Hun1Ahpu Avatar asked Dec 09 '22 13:12

Hun1Ahpu


2 Answers

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.

like image 133
steinar Avatar answered Dec 14 '22 23:12

steinar


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.

like image 25
Pieter van Ginkel Avatar answered Dec 14 '22 22:12

Pieter van Ginkel