I notice some issues with the Java float precision
Float.parseFloat("0.0065") - 0.001 // 0.0055000000134110451
new Float("0.027") - 0.001 // 0.02600000000700354575
Float.valueOf("0.074") - 0.001 // 0.07399999999999999999
I not only have a problem with Float but also with Double.
Can someone explain what is happening behind the scenes, and how can we get an accurate number? What would be the right way to handle this when dealing with these issues?
The problem is simply that
floathas finite precision; it cannot represent0.0065exactly. (The same is true ofdouble, of course: it has greater precision, but still finite.)A further problem, which makes the above problem more obvious, is that
0.001is adoublerather than afloat, so yourfloatis getting promoted to adoubleto perform the subtraction, and of course at that point the system has no way to recover the missing precision that adoublecould have represented to begin with. To address that, you would write:using
0.001finstead of0.001.