Home > Software design >  Convert string to double, but the first character is a dot
Convert string to double, but the first character is a dot

Time:10-31

I need to convert a string value similar to .904 and -.904 to a double. I haven't found any simple and direct way to do so, except to copy each character to another string and manually add the zero and then covert to double.

CodePudding user response:

Just make sure to specify a culture that supports that format when trying to convert from string to double, for example the culture-independent format CultureInfo.InvariantCulture.

using System;
using System.Globalization;
                    
public class Program
{
    public static void Main()
    {
        HandleSource("-.904");
        HandleSource(".904");
    }
    
    public static void HandleSource(string src)
    {
        double d = Double.Parse(src, CultureInfo.InvariantCulture);
        Console.WriteLine(d);
    }
}

https://dotnetfiddle.net/ftlYFE

When you don't specify an explicit culture and get the "Input string was not in a correct format" exception, this is because you run the code in an environment with a culture that uses comma as decimal separator.

CodePudding user response:

You can convert with the help of Convert.ToDouble function.

The small demo link I am attaching for your reference.

CodePudding user response:

I think this is the simplest way: https://dotnetfiddle.net/94UV1n

public static void Main()
{
    var s = "-.123";
    if (s[0]=='-') {
        Console.WriteLine(-double.Parse("0" s.Substring(1)));
    } else {
        Console.WriteLine(double.Parse("0" s));
    }
}
  • Related