How to print a C++ double with the correct number of significant decimal digits?

Is there a way to "pretty print" a float in C++ to the (assumed) correct number of significant figures?

Yes, you can do it with C++20 std::format, for example:

double test1 = 1.2593;
double test2 = 0.004963;
double test3 = 1.55558742563;
std::cout << std::format("{}", test1) << "\n";
std::cout << std::format("{}", test2) << "\n";
std::cout << std::format("{}", test3) << "\n";

prints

1.2593
0.004963
1.55558742563

The default format will give you the shortest decimal representation with a round-trip guarantee like in Java.

Since this is a new feature and may not be supported by some standard libraries yet, 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("{}", 1.2593);

Disclaimer: I'm the author of {fmt} and C++20 std::format.


I think you are talking about how to print the minimum number of floating point digits that allow you to read the exact same floating point number back. This paper is a good introduction to this tricky problem.

http://grouper.ieee.org/groups/754/email/pdfq3pavhBfih.pdf

The dtoa function looks like David Gay's work, you can find the source here http://www.netlib.org/fp/dtoa.c (although this is C not Java).

Gay also wrote a paper about his method. I don't have a link but it's referenced in the above paper so you can probably google it.