Converting double to string without scientific notation and without losing digits Requirements:


Must convert a double to a string, without losing any digits.
Cannot use scientific notation.


In C#, no format string exists that you can you pass into Double.ToString(format) to accomplish this, because ToString will use only 15 digits, even though a double can have 17. Although R and G17 can use 17 digits, it may or may not use scientific notation.

Please correct me if I am wrong.

Therefore, I wrote a function to do this. I'm posting it here as an optimization question. If you see flaws, feel free to point them out. I'm confident the code works, but there's plenty of room for improvement.

[Fact]
public void NumberFormats()
{
    double d1 = 123456789012171.23;
    double d2 = 0.0000000000000001;
    double d3 = 10000000000000000;

    string s1 = DoubleToString(d1);
    string s2 = DoubleToString(d2);
    string s3 = DoubleToString(d3);

    Assert.Equal("123456789012171.23", s1);
    Assert.Equal("0.0000000000000001", s2);
    Assert.Equal("10000000000000000", s3);
}

private string DoubleToString(double d)
{
    string R = d.ToString("R", CultureInfo.InvariantCulture).Replace(",", "");
    int i = R.IndexOf('E');

    if (i &lt; 0)
        return R;

    string G17 = d.ToString("G17", CultureInfo.InvariantCulture);

    if (!G17.Contains('E'))
        return G17.Replace(",", "");

    // manual parsing
    string beforeTheE = R.Substring(0, i);
    int E = Convert.ToInt32(R.Substring(i + 1));

    i = beforeTheE.IndexOf('.');

    if (i &lt; 0)
        i = beforeTheE.Length;
    else
        beforeTheE = beforeTheE.Replace(".", "");

    i += E;

    while (i &lt; 1)
    {
        beforeTheE = "0" + beforeTheE;
        i++;
    }

    while (i &gt; beforeTheE.Length)
    {
        beforeTheE += "0";
    }

    if (i == beforeTheE.Length)
        return beforeTheE;

    return String.Format("{0}.{1}", beforeTheE.Substring(0, i), beforeTheE.Substring(i));
}
I know, it's a challenge convert your big doubles to string, but if you can use decimal instead of double, the conversion could be smooth.

static void Main(string[] args)
{
    decimal d1 = 123456789012171.23m;
    decimal d2 = 0.0000000000000001m;
    decimal d3 = 10000000000000000m;

    Console.WriteLine(d1);
    Console.WriteLine(d2);
    Console.WriteLine(d3);
}