0

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?

asclepix
  • 7,971
  • 3
  • 31
  • 41
Abhinav Raja
  • 349
  • 1
  • 5
  • 25
  • Related: [Is it possible to do modulo of a fraction](https://math.stackexchange.com/questions/864568/is-it-possible-to-do-modulo-of-a-fraction) – MC Emperor Jul 17 '23 at 20:20
  • 1
    See also: https://stackoverflow.com/questions/2947044/how-do-i-use-modulus-for-float-double – Greycon Jul 17 '23 at 20:23
  • 1
    have you checked the result of `x % y` - floating point primitives in java are not exact (`2.4 = 2.399999999999999911182...` and `0.2 = 0.200000000000000011102...`) so the remainder operator with `double` is not the best solution (maybe you can use `BigDecimal`) – user16320675 Jul 17 '23 at 20:43
  • If one of the answers has solved your problem, you can accept it by clicking the checkmark near the upper left of the answer. – David Conrad Jul 18 '23 at 13:51

3 Answers3

0

Try this:

if(Math.round(x*1000)%Math.round(y*1000))

This will not work for values with too many digits after the decimal point, but you can always use a bigger multiplier than 1000 if you need it.

DevNight89
  • 33
  • 9
0

Convert to BigDecimal using valueof (not the new BigDecimal(double) constructor) and then take the remainder and compare it with zero.

public static void main(String[] args) {
    double x = 2.4;
    double y = 0.2;
    System.out.format("%.1f is a multiple of %.1f: %b%n",
        x, y, isMultipleOf(x, y));
}

public static boolean isMultipleOf(double d1, double d2) {
    return BigDecimal.valueOf(d1).remainder(BigDecimal.valueOf(d2))
        .compareTo(BigDecimal.ZERO) == 0;
}
David Conrad
  • 15,432
  • 2
  • 42
  • 54
0

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
Reilas
  • 3,297
  • 2
  • 4
  • 17