Search code examples
c#.netstringtype-conversiondouble

How to convert string into double value in C#


I am building simple C# Winforms desktop app using .NET framework. I need to convert a string like "172.5632" into double value.

I tried Double.parse() and Convert.toString().

Both of them didn't work and I get an error

Input string is not in correct format exception

And if I changed . to , (dot to comma), then the exception disappears, but the converted double value is not correct.

I am using Visual Studio 2022 on Windows 10, and using .NET 4.7.2.

It is really weird as this is very basic issue.


Solution

  • It might be a culture thing, make sure to specify invariant culture format

    string doubleNumber = "172.5632";
    Console.WriteLine(double.Parse(doubleNumber, CultureInfo.InvariantCulture));
    // Output: 172.5632