In Python, what is a good way to round towards zero in integer division?

前端 未结 8 1679
隐瞒了意图╮
隐瞒了意图╮ 2020-12-09 09:45
1/2

gives

0

as it should. However,

-1/2

gives

-1
8条回答
  •  借酒劲吻你
    2020-12-09 10:07

    why reinvent the wheel, when there's a perfectly good math.trunc() function?

    import math
    print(math.trunc(-3.5))
    >>-3
    print(math.trunc(3.5))
    >>3
    

提交回复
热议问题