Android Question

Android: which operator for modulo (% doesn't work with negative numbers)

If I try

int a=(-2)%6


I get -2 instead of 4.

Why does it behave this way with negative numbers?

Answer

% does a remainder operation in Java.

To get a proper modulus, you can use the remainder in a function:

It's shortest using ternary operator to do the sign fixup:

private int mod(int x, int y)
{
    int result = x % y;
    return result < 0? result + y : result;
}

For those who don't like the ternary operator, this is equivalent:

private int mod(int x, int y)
{
    int result = x % y;
    if (result < 0)
        result += y;
    return result;
}