How to format float unambiguously?

user1234 user1234 at 1234.de
Tue Aug 31 19:32:56 UTC 2021


On Tuesday, 31 August 2021 at 17:53:12 UTC, deadalnix wrote:
> When formatting floats, as far as I can tell, one either has to 
> pick the whole decimal gallery, or accept that the end result 
> might be ambiguous.
>
> For instance:
>
> writefln!"%f"(1.);  // 1.000000
> writefln!"%F"(1.);  // 1.000000
> writefln!"%#f"(1.); // 1.000000
> writefln!"%#F"(1.); // 1.000000
> writefln!"%g"(1.);  // 1
> writefln!"%G"(1.);  // 1
> writefln!"%#g"(1.); // 1.000000
> writefln!"%#G"(1.); // 1.000000
>
> Specifying the precision allows to reduce it, but not increase 
> it:
>
> writefln!"%.1f"(1.0);  // 1.0
> writefln!"%.1f"(1.11111);  // 1.1
>
> Am I missing something? This problem also seem to exist when 
> dumping value in D format. For instance:
>
> writeln([1.0]); // [1]
>
> Which is now an array of integers instead of floats.

ah yes, what a mess, IIRC it's

- %.8g for floats
- %.18g for doubles

%f is a known source of problem when dealing with 
serialization... like "1" looks like an integer.


More information about the Digitalmars-d mailing list