How does Java accurately display doubles, while it cannot be accurately expressed in binary scientific notation?

From my point of view, when assigning any double value to a variable, it will perform the following steps:

  • Convert to binary.
  • Make a few changes to the scientific notation format.
  • Convert to IEEE754.

Both steps 1 and step 3 may introduce some inaccuracy. Thus, the value stored in the memory is already inaccurate.

But it is amazing if I do not do any calculations on this double and just print it like this: println (0.2d)

or even

Println (1245.1325415d)

As long as the double is not too long, the result will always be accurate.

Are there any tricks when converting IEEE754 format to Base10 format?

+4
3

D , D. Double.toString D . " " , , String.

:

import java.math.BigDecimal;

public class Test {
  public static void main(String[] args) {
    double d1 = 0.4;
    double d2 = 0.400000000000000000001;
    System.out.println(d1);
    System.out.println(d2);
    System.out.println(new BigDecimal(d1));
  }
}

:

0.4
0.4
0.40000000000000002220446049250313080847263336181640625

"0,4" "0,400000000000000000001" , , 0,40000000000000002220446049250313080847263336181640625. 0.4 , toString. " " .

+4

print, double String.

, - , , , .

Unlimited, 6789.78848376767676... , .

..

System.out.println(67670.65656565656566665);

67670.65656565657, double String .

, , ...

String s=((Double)(67670.65656565656566665)).toString();
System.out.println(s);

.

+1

Double.toString() :

m a? , - , , , double.

: , . , , 0.xxxxx...x4999 0.xxxxx...x5, 0.xxxxx...x4837 0.xxxxx...x511 . : , .

+1

Source: https://habr.com/ru/post/1532617/


All Articles