What is the maximum length in chars needed to represent any double value?

Viewed 37600

When I convert an unsigned 8-bit int to string then I know the result will always be at most 3 chars (for 255) and for an signed 8-bit int we need 4 chars for e.g. "-128".

Now what I'm actually wondering is the same thing for floating-point values. What is the maximum number of chars required to represent any "double" or "float" value as a string?

Assume a regular C/C++ double (IEEE 754) and normal decimal expansion (i.e. no %e printf-formatting).

I'm not even sure if the really small number (i.e. 0.234234) will be longer than the really huge numbers (doubles representing integers)?

11 Answers

A correct source of information that goes into more detail than the IEEE-754 Specification are these lecture notes from UC Berkely on page 4, plus a little bit of DIY calculations. These lecture slides are also good for engineering students.

Recommended Buffer Sizes

| Single| Double | Extended | Quad  |
|:-----:|:------:|:--------:|:-----:|
|   16  |  24    |    30    |  45   |

These numbers are based on the following calculations:

Maximum Decimal Count of the Integral Portion

| Single| Double | Extended | Quad  |
|:-----:|:------:|:--------:|:-----:|
|   9   |   17   |    21    |  36   |

* Quantities listed in decimals.

Decimal counts are based on the formula: At most Ceiling(1 + NLog_10(2)) decimals, where N is the number of bits in the integral portion*.

Maximum Exponent Lengths

| Single| Double | Extended | Quad  |
|:-----:|:------:|:--------:|:-----:|
|   5   |   5    |     7    |   7   |
* Standard format is `e-123`.

Fastest Algorithm

The fastest algorithm for printing floating-point numbers is the Grisu2 algorithm detailed in the research paper Printing Floating-point Numbers Quickly and Accurately. The best benchmark I could find can be found here.

"For that you'll need exactly 325 characters"

Apparently (and this is a very common case) You don't understand the how the conversion between different numeric bases works.

No matter how accurate the definition of the DBL_MIN is, it is limited by hardware accuracy, which is usually up to 80 bits or 18 decimal digits (x86 and similar architectures)

For that reason, specialized arbitrary-precision-arithmetic libraries has been invented, like f.e. gmp or mpfr.

As an improvement on the accepted answer based on Greg A. Woods accurate comment, a more conservative but still adequate number of characters needed is 3 + DBL_DIG + -DBL_MIN_10_EXP (total 325) with 3 being for the leading "-0." that may be needed. If using C-style strings, add one for null ('\0') termination such that an adequately sized buffer (of size 326) may be created with:

#include <limits.h>

char buffer[4 + DBL_DIG + -DBL_MIN_10_EXP];

For those who prefer the C++ numeric limits interface that would be:

#include <limits>

char buffer[4 + std::numeric_limits<double>::digits10 + -std::numeric_limits<double>::min_exponent10];
Related