The standard header <float.h>
in C, or <cfloat>
in C++, contains several constants to do with the range and other metrics of the floating point types. One of these is DBL_MAX_10_EXP
, the largest power-of-10 exponent needed to represent all double
values. Since 1eN
needs N+1
digits to represent, and there might be a negative sign as well, then the answer is
int max_digits = DBL_MAX_10_EXP + 2;
This assumes that the exponent is larger than the number of digits needed to represent the largest possible mantissa value; otherwise, there will also be a decimal point followed by more digits.
CORRECTION
The longest number is actually the smallest representable negative number: it needs enough digits to cover both the exponent and the mantissa. This value is -pow(2, DBL_MIN_EXP - DBL_MANT_DIG)
, where DBL_MIN_EXP
is negative. It’s fairly easy to see (and prove by induction) that -pow(2,-N)
needs 3+N
characters for a non-scientific decimal representation ("-0."
, followed by N
digits). So the answer is
int max_digits = 3 + DBL_MANT_DIG - DBL_MIN_EXP
For a 64-bit IEEE double, we have
DBL_MANT_DIG = 53
DBL_MIN_EXP = -1023
max_digits = 3 + 53 - (-1023) = 1079