Floating point accuracy in literature versus computing

I am wondering why the floating point numbers in Java can represent the exact value when they are initialized as literals, but they are approximate when they represent the result of some calculations. For instance:

double num1 = 0.3;
double num2 = 0.1 + 0.2;
System.out.println(num1);
System.out.println(num2);

why the result:

0.3
0.30000000000000004

and not:

0.30000000000000004
0.30000000000000004

If there is no exact binary representation of 0.3. I know the BigDecimal class, but I do not quite understand the mismatch of these primitive numbers.

+4
source share
3 answers

double. , , , 0.1 0.2 , 0.3. 5.5E-17 , (demo).

double a = 0.2;
double b = 0.1;
double c = 0.3;
double d = a+b;
double e = d-c; //  This is 5.551115123125783E-17
+4

0,3 , , 0,3. , 0,1 0,2 , , , . IEEE . , , .

+2

0.3, 0.1 + 0.2 0.30000000000000004.

, System.out.println(0.3); println(double) : Double.toString(double), , :

m a? , , - , , , , double. , x - , , , d. d , x; x, d , d 0.

BigDecimal, :

System.out.println(0.3);  // 0.3
System.out.println(new BigDecimal(0.3));  // 0.299999999999999988897769753748434595763683319091796875
0

All Articles