是否有一个内置函数可以像下面这样舍入?

10 -> 10
12 -> 10
13 -> 15
14 -> 15
16 -> 15
18 -> 20

当前回答

我想还没有人写过这个,但你可以这样做:

round(12, -1) --> 10
round(18, -1) --> 20

其他回答

的值加上0.5,可以“欺骗”int()使其舍入而不是舍入 传递给int()的数字。

另一种方法(不需要显式的乘法或除法运算符):

def rnd(x, b=5):
    return round(x + min(-(x % b), b - (x % b), key=abs))

那么这个呢:

 def divround(value, step):
     return divmod(value, step)[0] * step

对已接受答案的补充,用于指定四舍五入到最接近的5或其他值

import math

def my_round(x, base, down = True):
    return base * math.floor(x/base) + (not down) * base

round(x[, n]):数值四舍五入到10的负n次方的最接近倍数。所以如果n是负的…

def round5(x):
    return int(round(x*2, -1)) / 2

由于10 = 5 * 2,您可以对2使用整数除法和乘法,而不是对5.0使用浮点除法和乘法。这并不重要,除非你喜欢位移位

def round5(x):
    return int(round(x << 1, -1)) >> 1