What is the difference when throwing float and double to int in java?

I used these statements for testing

float f=4.35f;
int i=(int)(f*100);
System.out.println(i);
double d=4.35;
i=(int)(d*100);
System.out.println(i);

result

 435
 434

I used to think that the only difference between float and double is just precision. They must be the same in the calculation. But I converted 4.35 to binary, and then converted it back to decimal and found that it was actually 4.3499999 ... Therefore, if I multiply it by 100 and then throw, I think the answer should be 434 floating and double. Why is the first one 435?

+4
source share
2 answers

Java . , 4.35, ( float, double ).

4.35 Java, double 435/100. 4.35f, float 435/100.

, 4.35, 4.35f 435/100: Java, 4.35 4.3499999999999996447286321199499070644378662109375 4.35f 4.349999904632568359375. , 435/100 (, , ).

, 435 a float, a double.

4.35f 4.35 100 ( float double ), :

  • 435, . 435. , Java , , 4.35. , 4.35. , 4.349999904632568359375. , 435. , 435 int int 435. , float.

  • 435. . int 434, . , double. 4.3499999999999996447286321199499070644378662109375 100 , double 435.0 ( double 434.99999999999994315658113919198513031005859375), , , double .

+6

Pascal Cuoq :

, 23 (float) 52 (double).

Java:

Java , , . , ; , . IEEE 754, .

: 4.35f . 100.0f, 435.0. , 4.35d 100.0d 434.99999999999994.... int, , 435 float 434 double, .

0

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


All Articles