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

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

当前回答

去掉“rest”会起作用:

rounded = int(val) - int(val) % 5

如果该值是一个整数:

rounded = val - val % 5

作为函数:

def roundint(value, base=5):
    return int(value) - int(value) % int(base)

其他回答

def round_up_to_base(x, base=10):
    return x + (base - x) % base

def round_down_to_base(x, base=10):
    return x - (x % base)

这给了

基础= 5:

>>> [i for i in range(20)]
[0, 1,  2,  3,  4,  5,  6,  7,  8,  9,  10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> [round_down_to_base(x=i, base=5) for i in range(20)]
[0, 0,  0,  0,  0,  5,  5,  5,  5,  5,  10, 10, 10, 10, 10, 15, 15, 15, 15, 15]

>>> [round_up_to_base(x=i, base=5) for i in range(20)]
[0, 5,  5,  5,  5,  5,  10, 10, 10, 10, 10, 15, 15, 15, 15, 15, 20, 20, 20, 20]

基础= 10:

>>> [i for i in range(20)]
[0, 1,  2,  3,  4,  5,  6,  7,  8,  9,  10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> [round_down_to_base(x=i, base=10) for i in range(20)]
[0, 0,  0,  0,  0,  0,  0,  0,  0,  0,  10, 10, 10, 10, 10, 10, 10, 10, 10, 10]

>>> [round_up_to_base(x=i, base=10) for i in range(20)]
[0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 20, 20, 20, 20, 20, 20, 20, 20, 20]

在Python 3.7.9中测试

我不知道Python中的标准函数,但这对我来说是可行的:

Python 3

def myround(x, base=5):
    return base * round(x/base)

很容易理解为什么上面的方法是有效的。你要确保你的数字除以5是一个整数,四舍五入正确。所以,我们首先做的就是(round(x/5))然后因为我们除以5,所以我们也乘以5。

我通过给它一个基本参数使函数更通用,默认值为5。

Python 2

在Python 2中,需要使用float(x)来确保/执行浮点除法,并且需要最终转换为int,因为在Python 2中round()返回的是浮点值。

def myround(x, base=5):
    return int(base * round(float(x)/base))

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

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

一个只适用于整型的解决方案(它接受浮点数,但舍入行为就像小数组件不存在一样),但不像任何依赖于临时转换到浮点数的解决方案(所有math.floor/math.浮点数)。基于天花板的解决方案,所有的解决方案使用/,大多数解决方案使用round),它适用于任意巨大的int输入,永远不会失去精度,永远不会引发异常或导致无穷大的值。

它是一个最简单的解决方案的改编,四舍五入到一个数字的下一个低倍数:

def round_to_nearest(num, base=5):
    num += base // 2
    return num - (num % base)

它所基于的四舍五入食谱是:

def round_down(num, base=5):
    return num - (num % base)

唯一的变化是你提前给数字加上一半的基数,所以它四舍五入到最接近的值。对于精确的中点值,只有偶数底数才可能,因此round_to_nearest(3,6)将舍入为6而不是0,而round_to_nearest(- 3,6)将舍入为0而不是-6。如果希望中点值向下舍入,可以将第一行更改为num += (base - 1) // 2。

那么这个呢:

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