是否有一个内置函数可以像下面这样舍入?
10 -> 10
12 -> 10
13 -> 15
14 -> 15
16 -> 15
18 -> 20
是否有一个内置函数可以像下面这样舍入?
10 -> 10
12 -> 10
13 -> 15
14 -> 15
16 -> 15
18 -> 20
当前回答
的值加上0.5,可以“欺骗”int()使其舍入而不是舍入 传递给int()的数字。
其他回答
对于整数和Python 3:
def divround_down(value, step):
return value//step*step
def divround_up(value, step):
return (value+step-1)//step*step
生产:
>>> [divround_down(x,5) for x in range(20)]
[0, 0, 0, 0, 0, 5, 5, 5, 5, 5, 10, 10, 10, 10, 10, 15, 15, 15, 15, 15]
>>> [divround_up(x,5) for x in range(20)]
[0, 5, 5, 5, 5, 5, 10, 10, 10, 10, 10, 15, 15, 15, 15, 15, 20, 20, 20, 20]
的值加上0.5,可以“欺骗”int()使其舍入而不是舍入 传递给int()的数字。
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中测试
另一种方法(不需要显式的乘法或除法运算符):
def rnd(x, b=5):
return round(x + min(-(x % b), b - (x % b), key=abs))
舍入到非整数值,例如0.05:
def myround(x, prec=2, base=.05):
return round(base * round(float(x)/base),prec)
我发现这很有用,因为我只需要在代码中进行搜索和替换,就可以将“round(”更改为“myround(”,而不必更改参数值。