Asoub
Asoub

Reputation: 2371

Why Java's int division rounds to zero?

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.


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

Answers (0)

Related Questions