是否有一个内置函数可以像下面这样舍入?
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()的数字。
其他回答
这只是一个比例的问题
>>> a=[10,11,12,13,14,15,16,17,18,19,20]
>>> for b in a:
... int(round(b/5.0)*5.0)
...
10
10
10
15
15
15
15
15
20
20
20
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中测试
Use:
>>> def round_to_nearest(n, m):
r = n % m
return n + m - r if r + r >= m else n - r
它不使用乘法,也不会从/转换为浮点数。
四舍五入到最接近10的倍数:
>>> for n in range(-21, 30, 3): print('{:3d} => {:3d}'.format(n, round_to_nearest(n, 10)))
-21 => -20
-18 => -20
-15 => -10
-12 => -10
-9 => -10
-6 => -10
-3 => 0
0 => 0
3 => 0
6 => 10
9 => 10
12 => 10
15 => 20
18 => 20
21 => 20
24 => 20
27 => 30
如你所见,它对负数和正数都适用。平局(例如-15和15)总是向上四舍五入。
一个类似的例子,四舍五入到5的最接近倍数,证明它也表现为不同的“基数”:
>>> for n in range(-21, 30, 3): print('{:3d} => {:3d}'.format(n, round_to_nearest(n, 5)))
-21 => -20
-18 => -20
-15 => -15
-12 => -10
-9 => -10
-6 => -5
-3 => -5
0 => 0
3 => 5
6 => 5
9 => 10
12 => 10
15 => 15
18 => 20
21 => 20
24 => 25
27 => 25
def round_to_next5(n):
return n + (5 - n) % 5
我想还没有人写过这个,但你可以这样做:
round(12, -1) --> 10
round(18, -1) --> 20