I have read several topics about the display of floating point numbers display in C++ and I couldn\'t find a satisfying answer.
My question is: how
In C++20 you'll be able to use std::format to do this:
std::cout << std::format("{}", M_PI);
Output (assuming IEEE754 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 using the precision of max_digits10
from std::numeric_limits
is that it doesn't print unnecessary digits. For example:
std::cout << std::setprecision(
std::numeric_limits::max_digits10) << 0.3;
prints 0.29999999999999999
while
std::cout << std::format("{}", 0.3);
prints 0.3
(godbolt).
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);
Disclaimer: I'm the author of {fmt} and C++20 std::format
.