In my earlier question I was printing a double
using cout
that got rounded when I wasn't expecting it. How can I make cout
print a double
using full precision?
In C++20 you can use std::format
to do this:
std::cout << std::format("{}", std::numbers::pi_v<double>);
Output (assuming IEEE 754 double
):
3.141592653589793
The default floating-point format is the shortest decimal representation with a round-trip guarantee. The advantage of this method compared to the setprecision
I/O manipulator is that it doesn't print unnecessary digits and is not affected by global state (see this blog post for more details).
In the meantime you can use the {fmt} library, std::format
is based on. {fmt} also provides the print
function that makes this even easier and more efficient (godbolt):
fmt::print("{}", M_PI);
The question doesn’t actually define what it means by "full precision". Normally it is understood as the precision enough for a round trip through decimal but there is another possible but unlikely interpretation of the maximum number of (significant) decimal digits. For IEEE 754 double the latter is 767 digits.
Disclaimer: I'm the author of {fmt} and C++20 std::format
.