Best way to make Java's modulus behave like it should with negative numbers?

fent picture fent · Dec 10, 2010 · Viewed 42.7k times · Source

In java when you do

a % b

If a is negative, it will return a negative result, instead of wrapping around to b like it should. What's the best way to fix this? Only way I can think is

a < 0 ? b + a : a % b

Answer

Peter Lawrey picture Peter Lawrey · Dec 10, 2010

It behaves as it should a % b = a - a / b * b; i.e. it's the remainder.

You can do (a % b + b) % b


This expression works as the result of (a % b) is necessarily lower than b, no matter if a is positive or negative. Adding b takes care of the negative values of a, since (a % b) is a negative value between -b and 0, (a % b + b) is necessarily lower than b and positive. The last modulo is there in case a was positive to begin with, since if a is positive (a % b + b) would become larger than b. Therefore, (a % b + b) % b turns it into smaller than b again (and doesn't affect negative a values).