Python3 rounding to nearest even

后端 未结 3 1680
悲哀的现实
悲哀的现实 2020-12-31 02:54

Python3.4 rounds to the nearest even (in the tie-breaker case).

>>> round(1.5)
2
>>> round(2.5)
2

But it only seems to do

3条回答
  •  清歌不尽
    2020-12-31 03:50

    Martijn got it exactly right. If you want an int-rounder to round to the nearest even, then I would go with this:

    def myRound(n):
        answer = round(n)
        if not answer%2:
            return answer
        if abs(answer+1-n) < abs(answer-1-n):
            return answer + 1
        else:
            return answer - 1
    

提交回复
热议问题