Search code examples
c#stringparsingdoublec#-5.0

double.TryParse() ignores dots in my string


So I'm currently using the following code to parse a string into a double:

double.TryParse(resultLabel.Content.ToString(), out newNumber);

The parsing is executed but it ignores the . in the code. For Example:

  • 3.3 gets parsed to 33
  • 6.7 gets parsed to 67
  • 9.5 gets parsed to 95

Does anyone know why is that and how to fix it?

Thanks in advance!

I tried to track it down with break points where it it parses falsely and it was immediately after this line.


Solution

  • You need to pass culture that use "." as decimal separator (e.g. InvariantCulture)

    var resultLabel = "3.3";
    var success = double.TryParse(resultLabel, out var newNumber); //success is false
    success = double.TryParse(resultLabel, NumberStyles.Any, CultureInfo.InvariantCulture, out newNumber); //success is true