What is the difference between int() and floor() in Python 3?

后端 未结 2 2108
死守一世寂寞
死守一世寂寞 2020-11-30 02:39

In Python 2, floor() returned a float value. Although not obvious to me, I found a few explanations clarifying why it may be useful to have floor()

2条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-30 03:17

    floor() rounds down. int() truncates. The difference is clear when you use negative numbers:

    >>> import math
    >>> math.floor(-3.5)
    -4
    >>> int(-3.5)
    -3
    

    Rounding down on negative numbers means that they move away from 0, truncating moves them closer to 0.

    Putting it differently, the floor() is always going to be lower or equal to the original. int() is going to be closer to zero or equal.

提交回复
热议问题