简体   繁体   中英

Double.Parse for Native language support

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?

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);

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.

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM