如果我得到数字46,我想要四舍五入到最接近的十。我怎么能在python中做到这一点?
46岁到50岁。
答案 0 :(得分:85)
round
确实采用了负ndigits
参数!
>>> round(46,-1)
50
可以解决你的问题。
答案 1 :(得分:46)
您可以使用math.ceil()
向上舍入,然后乘以10
import math
def roundup(x):
return int(math.ceil(x / 10.0)) * 10
只使用
>>roundup(45)
50
答案 2 :(得分:14)
这是一种方法:
>>> n = 46
>>> (n + 9) // 10 * 10
50
答案 3 :(得分:5)
这也将正确向下舍入:
>>> n = 46
>>> rem = n % 10
>>> if rem < 5:
... n = int(n / 10) * 10
... else:
... n = int((n + 10) / 10) * 10
...
>>> 50