How do you deal with Java’s weird behaviour with the modulus operator when using doubles?
For example, you would expect the result of 3.9 - (3.9 % 0.1) to be 3.9 (and indeed, Google says I’m not going crazy), but when I run it in Java I get 3.8000000000000003.
I understand this is a result of how Java stores and processes doubles, but is there a way to work around it?
Use a precise type if you need a precise result:
Why 3.8000…003? Because Java uses the FPU to calculate the result. 3.9 is impossible to store exactly in IEEE double precision notation, so it stores 3.89999… instead. And 3.8999%0.01 gives 0.09999… hence the result is a little bit bigger than 3.8.