Search code examples
c#stringparsingdoubleexponent

System.FormatException when parsing String to double


the Code worked fine in Unity. Now I'm using the samecode in a console Project and im getting a System.FormatException exception.

The code is:

private double ConvertToNumber(string number)
        {      
            return double.Parse(number, numberStyle);
        }

parameter when calling are:

number = "3.138924e-002"
numberStyle = NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign

Does anyone see the Error, or knows what might caus this?


Solution

  • The exception is thrown because the string you are providing cannot be converted to a number using the format you specified and your own current cultrue. The latter is implict unless you specify it.

    If you are reading this value from a database, you should use the invariant culture (i.e. a culture designed to persist numbers and dates in a consistent way in whatever place you need, except user interfaces).

    Your code becomes:

    return double.Parse(number, numberStyle, System.Globalization.CultureInfo.InvariantCulture);
    

    Instead, if you need a specific culture, you need to pass the correct culture in place of the invariant one.