double.ToString("G_") doesn't work with large numbers

I’m having an issue where ToString with format code “G” for doubles or floats does not limit the number of digits for very large numbers, above say 10^19. It worked for small numbers down to 10^-300.

3.1416
31.416
314.16
3141.6
31416
3.1416E+05
3.1416E+06
3.1416E+07
3.1416E+08
3.1416E+09
3.1416E+10
3.1416E+11
3.1416E+12
3.1416E+13
3.1416E+14
3.1416E+15
3.1416E+16
3.1416E+17
3.1416E+18
3.14159265358979312E+19
3.14159265358979312E+20
...

I never heard anything about the problem above. Now I have noticed on a related note that ‘double.ToString(“G_”)’ also displays incorrect values for the significand above ~10^62. The value of x remains correct, but the string representation is wrong.

This code produces the output below it:

    static void Main()
    {
        double x = 1;
        string s;
        while(x < double.MaxValue)
        {
            s = x.ToString("G4");
            Debug.WriteLine(s);
            x *= 10;
        }
    }

…1.0E+60
1.0E+61
1.0E+62
1.66E+63
1.66E+64
1.66E+65…

1 Like