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

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

gives

0

as it should. However,

-1/2

gives

-1
8条回答
  •  失恋的感觉
    2020-12-09 10:21

    Try this. Only works for numbers greater than -1

    import math
    
    x = .5
    y = -.5
    
    print math.floor(math.fabs(x))
    >> 0
    
    print math.floor(math.fabs(y))
    >> 0
    

提交回复
热议问题