Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the maximum length of Double.toString(d)?

Tags:

java

My experimentation suggests a bound of 24, which is reached by -Double.MIN_NORMAL, which results in

-2.2250738585072014E-308

...but I can't prove it, nor come up with a conclusive reason why no other value should beat -MIN_NORMAL.

like image 212
Louis Wasserman Avatar asked Jan 15 '14 19:01

Louis Wasserman


People also ask

What is the maximum value of double in Java?

MAX_VALUE. A constant holding the largest positive finite value of type double , (2-2-52)·21023. It is equal to the hexadecimal floating-point literal 0x1.

How many characters are a double in C++?

Double: The C++ double is also a primitive data type that is used to store floating-point values up to 15 digits. In the above example, variables of float and double types are initialized with floating-point values.


2 Answers

It's a 64-bit IEEE-754 float.

The most decimal numbers that can be stored in a 52-bit mantissa is 17 (see page 4: ceil( 1 + N Log10(2) )), so that's 19 characters with the decimal point and negative sign.

The bias is 1023, so the smallest base-2 exponent is 2^-1022, which is around 10^-308, so the longest exponent is 5 characters with the 'E' and negative sign.

19 + 5 == 24

like image 155
Glenn Lane Avatar answered Oct 01 '22 05:10

Glenn Lane


26 seems to be an upper bound, for certain, as follows.

According to GrepCode's version of FloatingDecimal.getChars, OpenJDK7 asserts that the value nDigits is at most 19. Looking at the code, nDigits appears to refer to the digits (not the decimal point) of the mantissa: in the above example, 22250738585072014. Additional characters, then, include

  • a - sign on the value as a whole
  • the . decimal point
  • the E for the exponent
  • a - sign on the exponent
  • at most three decimal digits on the exponent

... which makes 19 + 7 = 26.

(Arguments for tighter bounds are still welcome.)

like image 29
Louis Wasserman Avatar answered Oct 01 '22 05:10

Louis Wasserman