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?
You're getting the right results. There is no such
float
as 0.027 exactly, nor is there such adouble
. You will always get these errors if you usefloat
ordouble
.float
anddouble
are stored as binary fractions: something like 1/2 + 1/4 + 1/16... You can't get all decimal values to be stored exactly as finite-precision binary fractions. It's just not mathematically possible.The only alternative is to use
BigDecimal
, which you can use to get exact decimal values.