Search code examples
javamodulo

How to check if a number (type double) is multiple of another number (type double)?


Example I want to check if x = 2.4 is a multiple of y = 0.2. I have used the modulus operator but it is giving result as false.

I have tried

if (x % y == 0 )   // Giving False
if (x % y == 0.0 )   // Giving False
if (x % y == 0.00 )   // Giving False

Is there another way to check for this?


Solution

  • The BigDecimal class will give you the precision you're looking for.

    BigDecimal x = new BigDecimal("2.4");
    BigDecimal y = new BigDecimal("0.2");
    double remainder = x.remainder(y).doubleValue();
    System.out.println(remainder);
    

    Output

    0.0
    

    Make sure to provide your data as String values, otherwise the same floating-point error will occur.
    The BigDecimal#valueOf method will suffice as well.  You can use String#valueOf if need be.

    For example,

    BigDecimal x = new BigDecimal(2.4d);
    BigDecimal y = new BigDecimal(0.2d);
    double remainder = x.remainder(y).doubleValue();
    System.out.println(remainder);
    

    Output

    0.1999999999999998