Skip to content
Advertisement

Float converted into int for big values

I have just a basic question that why there are discrepancies between the below statements?

System.out.printf("%.2f n", 55050000.41f);
System.out.printf("%.2f n", 50.41f);

Output

55050000.00 
50.41 

The first statement removed a decimal value and why not for 2nd statement?

Advertisement

Answer

By default floating point numbers in Java are converted to 64bit double, but since you’re using the f suffix the number will be interpreted as a 32bit float.

The number is so big that it doesn’t fit 32bit without losing precision and 55050000 is the closest possible number.

You can play around with floats here. If you change the last bit you can see the number increases by 4.

You probably don’t want to use the f suffix unless you’re working with limited space.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement