c++formattingc++17number-formatting

std::to_chars() minimal floating point buffer size


Given a generic integer type IntType, it is easy to determine the necessary buffer type for a std::to_chars operation for base-10 numbers:

std::array<char, std::numeric_limits<IntType>::digits10 + 1 +
                 std::is_signed<IntType>::value> buf;

Since std::to_chars doesn't NUL-terminate, and only adds the digits (and a possible preceding '-', if signed), this should work for all built-in integer types. The + 1 is needed because digits10 for integral types returns the floor of the base-10 logarithm, not the ceiling.

This leads to the question: what is the minimal buffer size for a floating point std::to_chars call given a generic FloatType to be converted without loss (writing all decimal digits), using each of the std::chars_format values?


Solution

  • Note that the minimal buffer required is different depending on the floating point format desired. Using max_digits10 and max_exponent10 is always enough to determine the minimum number of characters necessary for base-10 output, assuming one doesn't want to output more precision than the floating point type contains.

    This problem is not just limited to to_chars, either. The C standard library functions in the printf family will have the same behavior, so this applies with equal weight in C as it does in C++.

    Note that in all these examples, the buffer is exactly the size of the largest string representation. If a NUL-terminator or other content is needed, the size must be increased accordingly.