HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcppCritical

How do I print a double value with full precision using cout?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
doublewithhowfullusingprintcoutvalueprecision

Problem

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?

Solution

In C++20 you can use std::format to do this:

std::cout );


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.

Code Snippets

std::cout << std::format("{}", std::numbers::pi_v<double>);
fmt::print("{}", M_PI);

Context

Stack Overflow Q#554063, score: 119

Revisions (0)

No revisions yet.