Basically, floating point values โโare stored as a pair of mantissa and exponent. Mantissa describes the significant digits of a number (consider this a number from 0 to 9.99). The indicator is scale. Your number is represented as mantissa * 2 ^ x.
We are talking about a representation in the binary system that even direct numbers (in decimal), such as 35912062, do to something that may not exactly match the accuracy of the mantissa. In these cases, you get some rounding problems, especially since the float has a limited range for the mantissa.
Executing code using double (instead of float) gives the result 3.5912062E7.
If you really want to know what java (or floating point arithmetic) does of your number, you should do System.out.println(new Bigdecimal(123.456)) and be surprised.
The message here is, if you really need accurate arithmetic, always take BigDecimal. Because there are additional reservations. For example, adding a large double and a small double can cause the small double to be completely rounded. This leads us to the funny:
for (float f = 35912062f; f < 55912062f; f++) { System.out.println(f); }
will never stop. Just give it a try.
source share