javainteger-division

Why do integer div and mod round towards zero?


Unlike in C, in Java is the result of x/y and x%y well-defined even for negative operands. Surprisingly, it's defined by rounding towards zero, and not by rounding down (i.e., towards negative infinity). Does anybody have taken any advantage of this definition?

In most cases I just don't care, but sometimes I had to work around this, e.g., when computing an index using modulo array.length.

This is no rant, I'm really interested if there are uses for this definition.


Solution

  • It's easier to implement a division routine if you can round toward zero. Often, a division involving a negative is sign-flipped, and then the division carried out on a positive equivalent, and then the answer flipped back again. So the effect is naturally going to be round toward zero.