Reputation: 627
I have a value 20,55
which is in German language.
When I change the regional settings to US the value gets displayed as 2055.0
after running this code:
double d = Double.Parse("20,55",CultureInfo.CurrentCUCulture);
Why is that?
Upvotes: 2
Views: 1341
Reputation: 111870
Because in US the ,
is the thousand separator and it's ignored? In the same way that in Germany (and continental Europe) the .
is the thousand separator and it's ignored?
In Germany you write: 1.000,55. In USA you write: 1,000.55 (and there are some schools of thought that remove the ,
if there is a single digit before. So 1000.55 and 11,000.55).
Now, if you want to be sure your program is using the de-DE
culture, pass as a parameter everywhere
CurrentCulture culture = new CultureInfo("de-DE");
double d = double.Parse("20,55", culture);
Upvotes: 4
Reputation: 18743
It's because the US decimal separator is the .
and not the ,
.
If you want to avoid that problem no matter the regional settings of the user, you could write a extension method:
public static String ToRegionalNumber(this String str) {
String regionalNb = str.Replace(",", NumberFormatInfo.CurrentInfo.NumberDecimalSeparator);
regionalNb = regionalNb .Replace(".", NumberFormatInfo.CurrentInfo.NumberDecimalSeparator);
return regionalNb ;
}
And call this method when working with your number:
double d = Double.Parse("20,55".ToRegionalNumber());
Upvotes: 1
Reputation: 881553
In the US, the decimal separator is .
, not ,
. If you attempt to parse 20,55
, it will (apparently) ignore the commas as standard triplet separators (such as in 1,234,567.89
), even though there aren't three digits in all of them.
If you want to parse a Euro-style number, you need to parse it with a Euro-style culture setting.
Upvotes: 3