The binary representation for 0.1 is
System.out.println(new BigDecimal(0.1));
prints
0.1000000000000000055511151231257827021181583404541015625
When you type 0.1, you get a small amount of rounding that hides this error.
When you do the calculation, you should use BigDecimal to either round the result or transform the calculations to minimize the error.
5 % 0.1 (5 / 0.1 % 1) * 0.1 50 % 1 / 10
In terms of double you can do
double d = 5; double mod0_1 = d * 10 % 1 / 10; double rounded = Math.round(mod0_1 * 1e12)/1e12;
Note: the result may still have a small error, but it will be small enough that you will not see it when printing it.
source share