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

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

gives

0

as it should. However,

-1/2

gives

-1
8条回答
  •  余生分开走
    2020-12-09 10:17

    You can also use the Decimal module as part of the standard python libraries.

    Specifically, " The integer division operator // behaves analogously, returning the integer part of the true quotient (truncating towards zero) rather than its floor, so as to preserve the usual identity x == (x // y) * y + x % y:"

    >>> -7 // 4
    -2
    >>> Decimal(-7) // Decimal(4)
    Decimal('-1')
    

    Also, have a look at Rounding Modes as they've got quite a few ways to view/round your information - Ceiling, down, floor, half-down, half-even, half-up, up and 05up rounding.

    Decimal was written as a solution to the traditional problem of binary mathematics in a world expecting decimals solutions

提交回复
热议问题