formatting a float or double in a string with all significant digits kept
GreatSam4sure
greatsam4sure at gmail.com
Wed Oct 9 09:35:36 UTC 2019
On Wednesday, 9 October 2019 at 07:16:43 UTC, Jon Degenhardt
wrote:
> On Wednesday, 9 October 2019 at 05:46:12 UTC, berni44 wrote:
>> On Tuesday, 8 October 2019 at 20:37:03 UTC, dan wrote:
>>> 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.
>>
>> You can use the property .dig to get the number of significant
>> digits of a number:
>>
>> writeln(PI.dig); // => 18
>>
>> You still need to account for the numbers before the dot. If
>> you're happy with scientific notation you can do:
>>
>> auto t = format("%.*e", PI.dig, PI);
>> writeln("PI = ",t);
>
> Using the '.dig' property is a really nice idea and looks very
> useful for this. A clarification though - It's the significant
> digits in the data type, not the value. (PI is 18 because it's
> a real, not a double.) So:
>
> writeln(1.0f.dig, ", ", float.dig); => 6, 6
> writeln(1.0.dig, ", ", double.dig); => 15, 15
> writeln(1.0L.dig, ", ", real.dig); => 18, 18
>
> Another possibility would be to combine the '.dig' property
> with the "%g" option, similar to the use "%e" shown. For
> example, these lines:
>
> writeln(format("%0.*g", PI.dig, PI));
> writeln(format("%0.*g", double.dig, 1.0));
> writeln(format("%0.*g", double.dig, 100.0));
> writeln(format("%0.*g", double.dig, 1.00000001));
> writeln(format("%0.*g", double.dig, 0.00000001));
>
> produce:
>
> 3.14159265358979324
> 1
> 100
> 1.00000001
> 1e-08
>
> Hopefully experimenting with the different formatting options
> available will yield one that works for your use case.
Good solution
But what does it takes to leave a number the way it is without
formatting automatic to 6 significant figure out how that
requires such a work around as shown above. I know C language is
the same but must D follow suit.
One of the compilers, i think the DMD 2.084 (not sure now)
correct but now the recent one's have revert back. Every number
should be left the way it is like java, C#(not sure),
actionscript, javascript, etc.
I don't think it will take that much effort for trivial things
like to stress developers.
This is the best solution i have ever seen on this issue on the
forum.i have ask this question several times on this forum
More information about the Digitalmars-d-learn
mailing list