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

dan dan.hitt at gmail.com
Thu Oct 10 17:12:25 UTC 2019


On Wednesday, 9 October 2019 at 10:54:49 UTC, David Briant wrote:
> 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

Thanks David for your reply.

Thanks also berni44 for the information about the dig attribute,
Jon for the neat packaging into one line using the attribute on 
the type.
Unfortunately, the version of gdc that comes with the version of 
debian
that i am using does not have the dig attribute yet, but perhaps 
i can
upgrade, and eventually i think gdc will have it.

And thanks GreatSam4sure for your reply --- i searched the 
archives first,
but very poorly :(.  But it's easy to believe that i'm not the 
first person
in the history of the world with this issue.

Now, my use case is nothing so useful or general as a csv/json 
reader/writer.

I'm just doing some computations, incorrectly i think, and i want 
to be
able to print out the results and feed them to other software.  
I'm trying
to chase down a problem and rule out as many places for error as 
i can, and
it just seemed strange not to be able to get all the digits out 
in some easy way.
But the dig attribute seems to be a big step forward, and for 
that i am grateful.

dan


More information about the Digitalmars-d-learn mailing list