formatting a float or double in a string with all significant digits kept

David Briant dbriant at symmetryinvestments.com
Wed Oct 9 10:54:49 UTC 2019


On Tuesday, 8 October 2019 at 20:37:03 UTC, dan wrote:
> I have a double precision number that i would like to print all 
> significant digits of, but no more than what are actually 
> present in the number.  Or more exactly, i want to print the 
> minimum number of digits necessary to recover the original 
> number to within 2 or 3 least significant bits in the stored, 
> in-core, version of its bit pattern.
>
> For example,
>
>
> import std.string;
> import std.stdio;
> import std.math;
>
> void main( ) {
>   auto t = format("%3.30f", PI );
>   writeln("Value of PI is: ", PI, " or, : ", t);
> }
>
> The default way writeln prints is 5 digits to the right of the 
> decimal point.
>
> I can format to print with any number of digits, such as 30 
> above, but that's too many.
>
> For pi, the correct number of digits to print looks to be about 
> 18 (and the extra 12 digits presumably are from the decimal 
> expansion of the least significant bit?).
>
> But i would like to be able to do this without knowing the 
> expansion of pi, or writing too much code, especially if 
> there's some d function like writeAllDigits or something 
> similar.
>
> Thanks in advance for any pointers!
>
> dan

Hi Dan,

What's your usecase here, e.g. a csv/json reader / writer? You 
say it's for double precision numbers (64bit format) then provide 
an example for reals (80bit format). So I'm not certain your goal.

If you google "what every developer should know about doubles" 
you'll hit a number of useful articles that explain the common 
issues of floating point representation in detail.

-- David


More information about the Digitalmars-d-learn mailing list