C# convert string to double in locale

clamp picture clamp · Sep 14, 2012 · Viewed 17.4k times · Source

In my locale the decimal separator is a ','.

However I would still like to write a C# application which works with numbers that use the '.' as decimal separator.

        string b = "0,5";
        double db = double.Parse(b); // gives 0.5

        string a = "0.5";
        double da = double.Parse(a); // gives 5, however i would like to get 0.5

Answer

Jon Skeet picture Jon Skeet · Sep 14, 2012

You need to specify the culture as the second argument to double.Parse, e.g.

double da = double.Parse(a, CultureInfo.InvariantCulture);

Pretty much all of the formatting/parsing methods have overloads taking an IFormatProvider, and the most commonly-specified implementation of IFormatProvider is CultureInfo.