Modulus with doubles in Java

Use a precise type if you need a precise result:

    double val = 3.9 - (3.9 % 0.1);
    System.out.println(val); // 3.8000000000000003

    BigDecimal x = new BigDecimal( "3.9" );
    BigDecimal bdVal = x.subtract( x.remainder( new BigDecimal( "0.1" ) ) );
    System.out.println(bdVal); // 3.9

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.

Leave a Comment