Java operators not operating correctly (8.99%1=0.990000002)

Can someone please explain why is this happening, the operators are adding numbers during the operation.
image

It’s down to the way floating point values are typically stored in computer memory and Floating-point arithmetic - Wikipedia. Storing infinite precision isn’t possible, especially for irrational numbers like pi and mathematical operations on floats often result in approximations.

For dealing with this a good option is to work with integers when performing mathematical operations (with currency for example use the smallest value e.g. cents instead of dollars) if at all possible. There may be some but less precision loss if you can refactor or use libraries to work with rational numbers most of the time (keeping exponent and quotient for division), or, in cases where you’re performing only a few operations and aren’t worried about the precision of the nth digit you can truncate/round the result in some way when printing.

Have a look for floating point (arithmetic) and Java in particular (it’s not just Java affected but for what you want to do specifying the language is useful) and you’ll find some excellent resources explaining and then trying to deal with this.

2 Likes

Thank you very much :slightly_smiling_face:
Now I got it! :+1:

1 Like