Reputation: 2092
I want to print doubles in decimal notation with full precision (but without extra zeros at the end of the number). In C++ I can use:
std::setprecision(20);
cout << d; // Here d is a double
What would be the equivalent C code using printf?
Upvotes: 6
Views: 16499
Reputation: 33645
Format is typically: %[flags][width][.precision][length]specifier
, so for example, %.20f
If you pass in .*
rather than .20
, you can pass in an arbitrary precision at run time before the decimal value.
NOTE: you can use g
too, however you should note that in some cases, there will be a difference in the result (between f
and g
- due to the way that the precision is interpreted.)
The main question though is what do you need that kind of precision for? (double/floats are imprecise)...
Upvotes: 8
Reputation: 37208
You can use the "%.20g" specifier. g is IMHO usually better than f since it doesn't print trailing zeros, and handles large/small values sensibly (changing to e format).
Also note that with the "g" specifier, the precision (the "20" in this case) specifies the number of significant digits rather than the number of digits after the decimal point.
Upvotes: 14
Reputation: 361532
Use:
printf("%.20f", d);
That should work.
Taken from an online doc, the more general format is:
%[flags][width][.precision][length]specifier
Go through the link to read about each token in the format.
Upvotes: 4