Since the 1990s it is known how to print floating-point numbers quickly and accurately. The Scheme and Java programming languages have implemented this algorithm, but I couldn't find anything similar in C++.
Essentially, I'm looking for a small, efficient piece of code that satisfies the following test cases:
void test(double dbl, const char *expected) {
std::string actual = ...;
assert(actual == expected);
}
test(3.0, "3.0");
test(3.1, "3.1");
test(0.1, "0.1");
test(1.0 / 3.0, "0.3333333333333333"); // Or maybe one more digit?
The double literal is converted to a floating-point number, which may or may not be the same as the literal. Then, the floating-point number is converted back to a string. This string should be as short as possible and at the same time represent the decimal number that, when interpreted as a double literal, will yield the same floating-point number again.
How do I print a double value with full precision using cout? looks related, but the code from the accepted answer doesn't handle the 3.1 case correctly.