Why, when I assign an int to a float, is this not the same value?

When I assign from an int float, I thought that the float allows more precision, so it won’t lose or change the assigned value, but what I see is something completely different. What's going on here?

for(int i = 63000000; i < 63005515; i++) { 
   int a = i;
   float f = 0; 
   f=a; 
   System.out.print(java.text.NumberFormat.getInstance().format(a) + " : " );
   System.out.println(java.text.NumberFormat.getInstance().format(f));
} 

output part:

...

63 005 504: 63 005 504

63 005 505: 63 005 504

63 005 506: 63 005 504

63 005 507: 63 005 508

63 005 508: 63 005 508

Thank!

+4
source share
5 answers

A float , int - 32 . , int. 24 ( 23 "" 1 1). 63 000 000 1. Math.ulp, .

System.out.println(Math.ulp(63000000.0f));

4.0

double ( ) :

System.out.println(Math.ulp(63000000.0));

7.450580596923828E-9

int , 63 int, 2 .

+14

java IEEE 754, ± 1.40129846432481707e-45 ± 3.40282346638528860e + 38, 6 7 .

double, 14 - int.

, , , , BigInteger BigDecimal.

+2

, . Int float 32 , , , int. , , , , - BigDecimal.

+1

, .

2 ^ 32 () -2 * 10 ^ 9 2 * 10 ^ 9. 32 , , .

32 , - . , ( 10-base) mantisa * 10^exponent.

, , . , , , , , .

+1

Float , .

Int , .

Int 1, Float - 4.

So, if you're dealing with trillions but don't care about +/- 4, use float. but if you need the last digit to be exact, you need to use int.

0
source

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


All Articles