Difference between Convert.ToDouble and double.Parse in correlation with InvariantCulture

Viewed 7844

I am wondering why this is working:

doubleValue = double.Parse(input[0].ToString(System.Globalization.CultureInfo.InvariantCulture).Replace(',', '.'), System.Globalization.CultureInfo.InvariantCulture);

while this isn't:

doubleValue = Convert.ToDouble(input[0])

The point is, there are about 30 machines in one country (same Windows image, same hardware, different location). While the first 20 machines are fine with Convert.ToDouble(), the 10 other ones can't convert the values properly (They loose the decimal point in every case, no matter if point or comma).

Since the program is really big an complex, is there an opportunity to get Convert.ToDouble() working without changing the program itself?

Another point is, i tried different methods to convert my string value to a double, none of them are working but only the double.Parse()...

And also, is it generally bad to use Convert.ToDouble() vor strings? (Only for objects)

Edit:

I created this method inside my class:

public static double ToDouble(string value, IFormatProvider provider)
{
    if (value == null)
    {
        return 0.0;
    }

    return double.Parse(value, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite | NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands | NumberStyles.AllowExponent, provider);
}

and called it with (tried also points and commas):

doubleValue = ToDouble(myTextBox.Text, CultureInfo.InvariantCulture);

Result: Still not working...

3 Answers

As I remember, Convert.ToDouble() looks like this:

// System.Convert
public static double ToDouble(string value)
{
    if (value == null)
    {
        return 0.0;
    }
    return double.Parse(value, CultureInfo.CurrentCulture);
}

As you can see, internally it calls double.Parse() method, with CurrentCulture. So if you've got a string, and you expect it to always be a double, use double.Parse() with the culture you prefer.

P.S. Yeap, I was right, you can look in mscorlib.dll with ILSpy.

P.P.S I forgot about ReferenceSource resource, so you can find out same thing Here.

Convert.ToDouble uses current thread culture so you cannot specify explicitly the culture you want to cast.

Whereas double.Parse provides you an overload to specify the culture you want to parse into, that's the reason why Convert.ToDouble is not working on some of your machines.

Related