Reputation: 2371
I've found that the rule for rounding two int in Java is to get the value closer to 0.
Which mean that if you divide two positive numbers, you get the "floor" value e.g 7/3=2
.
And if you divide one negative value by a positive one (or vice versa), you get the "ceiling" value: -7/3 = -2
.
I would expect to be either both floor or ceiling value.
Is it because the "negative" is evaluated after the division ?
It it some legacy over C ?
Is it to stay consistant with some transitive operation of the remainder (% operator) ?
(i.e (a+(a%b)/b = ceiling(a/b)
and (a-(a%b)/b = floor(a/b)
)
One of the comment has the definitive answer I was looking for: it is specified in Java's official documentation: https://docs.oracle.com/javase/specs/jls/se23/html/jls-15.html#jls-15.17.2-200
Integer division rounds toward 0.
As a lot of people also commented: it most likely comes from C, which comes from CPU implementation of integer division.
The C norm is described here: https://stackoverflow.com/a/3604984/5190019 and it also says that C did it that way because Fortran also did.
The linked question ( Why do integer div and mod round towards zero?) explains how usual division with negative number occurs: division is made as if both number were positive, then it's transformed to the equivalent negative number.
Originally, it certainly comes from the easiest way to perform integer division with a CPU (with negative numbers using "two's complement" representation).
Upvotes: 1
Views: 103