是否有一个内置函数可以像下面这样舍入?
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()的数字。
其他回答
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
去掉“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_to_next5(n):
return n + (5 - n) % 5
对于整数和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]
对已接受答案的补充,用于指定四舍五入到最接近的5或其他值
import math
def my_round(x, base, down = True):
return base * math.floor(x/base) + (not down) * base