float x = 0.98123452f;
System.out.println(x); //it prints out 0.9812345
float x = 0.98123453f;
System.out.println(x); //it prints out 0.98123455
I have no idea why the second one's output is 0.98123455 instead of 0.9812345. Isn't the precision of float is 7 decimal digits?
解决方案
The IEEE 754 float representation of
0.98123453
is 32 bits of (sign, exp, mantissa):
0 01111110 11110110011001000110000
which is:
0.9812345504760742
in double precision, and cast back to float decimal representation:
0.98123455
The number of bits allocated to a single precision (float) is 32, and 64 bits for double precision. Further note that BigDecimal that is frequently suggested will store your number as a string, and not in IEEE754 format. It will do a conversion when it needs to act on the number, and while it has a better precision, it is awfully slow.
EDIT. To clarify why it prints 0.98123455, we need to observe that it is the closest single precision representation of the number 0.98123453:
00111111011110110011001000101111 = 0.9812345 (sp) = 0.9812344908714294 (dp)
00111111011110110011001000110000 = 0.98123455 (sp) = 0.9812345504760742 (dp)
00111111011110110011001000110001 = 0.9812346 (sp) = 0.981234610080719 (dp)
sp = single precision, dp = double precision
The listing is for the [-1,+1] binary range around the number, and you can see that 0.98123453 is closest to the 10000 suffix of the mantissa, while 0.98123452 is closest to the 01111 suffix.