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

dan dan.hitt at gmail.com
Tue Oct 8 20:37:03 UTC 2019


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


More information about the Digitalmars-d-learn mailing list