Search code examples
c#parsing.net-coredoublec#-interactive

Parsing "1.5" with AllowDecimalPoint gives FormatException


When I try to run this code using the C# Interactive Compiler

double.Parse("1.5", System.Globalization.NumberStyles.AllowDecimalPoint);

I've this exception

System.FormatException: Input string was not in a correct format.
  + System.Number.ParseDouble(string, System.Globalization.NumberStyles, System.Globalization.NumberFormatInfo)
  + double.Parse(string, System.Globalization.NumberStyles)
  + <Initialize>.MoveNext()

I've read this from the documentation but I don't get wiser from it.

Indicates that the numeric string can have a decimal point. If the NumberStyles value includes the AllowCurrencySymbol flag and the parsed string includes a currency symbol, the decimal separator character is determined by the CurrencyDecimalSeparator property. Otherwise, the decimal separator character is determined by the NumberDecimalSeparator property.

Also code below gives me the same error:

double.Parse("1.500", System.Globalization.NumberStyles.AllowDecimalPoint);

Why I've this error? I expected that it gives me 1.5 as a double because decimal point is allowed.

Side note: My computer is configured to use a comma as a decimal separator meaning that code below works.

double.Parse("1,5", System.Globalization.NumberStyles.AllowDecimalPoint);

Solution

  • Add a third parameter to the call

    double.Parse("1.5", System.Globalization.NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture);
    

    This happens because your locale settings doesn't accept a point as decimal separator, so you need to add that parameter to explain that you are parsing a number where the decimal separator is a point.