是否有一个内置函数可以像下面这样舍入?
10 -> 10
12 -> 10
13 -> 15
14 -> 15
16 -> 15
18 -> 20
是否有一个内置函数可以像下面这样舍入?
10 -> 10
12 -> 10
13 -> 15
14 -> 15
16 -> 15
18 -> 20
当前回答
对已接受答案的补充,用于指定四舍五入到最接近的5或其他值
import math
def my_round(x, base, down = True):
return base * math.floor(x/base) + (not down) * base
其他回答
那么这个呢:
def divround(value, step):
return divmod(value, step)[0] * step
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
一个只适用于整型的解决方案(它接受浮点数,但舍入行为就像小数组件不存在一样),但不像任何依赖于临时转换到浮点数的解决方案(所有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 myround(x, base=5):
return base * round(float(x) / base)
这允许我们使用非整数进制,如。25或任何其他分数进制。
去掉“rest”会起作用:
rounded = int(val) - int(val) % 5
如果该值是一个整数:
rounded = val - val % 5
作为函数:
def roundint(value, base=5):
return int(value) - int(value) % int(base)