formatting a float or double in a string with all significant digits kept
berni44
dlang at d-ecke.de
Wed Oct 9 05:46:12 UTC 2019
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);
(By the way, you can shortcut that with writefln!"PI =
%.*e"(PI.dig, PI);)
If you don't want to use scientific notation, you probably need
to do some calculations to find out about the number of digits
before the dot (you need abs to make it work for negative numbers
too):
import std.conv: to;
auto x = to!int(log10(abs(PI)));
writefln!"%*.*f"(x,PI.dig-x,PI);
More information about the Digitalmars-d-learn
mailing list