Search code examples
pythonintfloor

Function int() rounding towards negative infinity (floor) or zero?


I see Why is -1/2 evaluated to 0 in C++, but -1 in Python? says integer division rounds towards infinity in Python, namely, floor is applied to the result.

I thought int(value) would also do something like floor, while I get int(-1.5) == -1 in practice, which was expected to be -2 in my mind.

So question is: why rules are inconsistent between integer division and function int()? Is there any reasonable explanation?


Solution

  • int() removes the decimal component; it doesn't do any rounding. From the documentation:

    If x is floating point, the conversion truncates towards zero.

    For turning a float into an int this is entirely logical behaviour. This is not division, flooring or otherwise.

    The // floor division operator otherwise clearly does floor, not truncate. In Python 2, for two integer operands, the / division also floors. The documentation again:

    the result is that of mathematical division with the ‘floor’ function applied to the result

    where math.floor() is documented as:

    Return the floor of x as a float, the largest integer value less than or equal to x.

    I see no inconsistency here; division floors, turning floats to integers truncates.