Full precision double to string conversion

Stanislav Blinov stanislav.blinov at gmail.com
Sat Nov 3 14:07:17 UTC 2018


On Saturday, 3 November 2018 at 13:20:22 UTC, Ecstatic Coder 
wrote:
> On Saturday, 3 November 2018 at 12:45:03 UTC, Danny Arends 
> wrote:

>>> How can I convert a double value -12.000123456 to its string 
>>> value "-12.000123456", i.e. without loosing double-precision 
>>> digits ?
>>
>> Specify how many digits you want with writefln:
>>
>> writefln("%.8f", value);
>
> Actually, what I need is the D equivalent of the default 
> ToString() function we have in Dart and C#.

I don't think it means what you think it means:

void main() {
     double value = -12.000123456;
     int precision = 50;

     import std.stdio;
     writefln("%.*g", precision, value);

     import std.format;
     string str = format("%.*g", precision, value);
     writeln(str);
}

Prints:

-12.000123456000000743415512260980904102325439453125
-12.000123456000000743415512260980904102325439453125

That's not quite the -12.000123456 that you'd get from C#'s 
ToString().

> I mean a dumb double-to-string standard library conversion 
> function which returns a string including all the double 
> precision digits stored in the 52 significant bits of the 
> value, preferably with the trailing zeroes removed.

All of them? Most implementations of conversion algorithms 
actually stop when it's "good enough". AFAIR, D doesn't even have 
it's own implementation and forwards to C, unless that changed in 
recent years.


More information about the Digitalmars-d-learn mailing list