Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Float converted into int for big values

Tags:

java

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?

like image 328
Vinit Solanki Avatar asked Mar 12 '21 09:03

Vinit Solanki


1 Answers

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.

like image 135
DerMaddi Avatar answered Oct 02 '22 17:10

DerMaddi