如何在python中找到最接近的等于或大于十的倍数

Shi*_*ndi 2 python rounding floor ceil

我有一个这个小任务,我将数字四舍五入到十的更高倍数。但是想要将其四舍五入到最接近的十的倍数。

我的代码:

import math

a = map(int,list(str(7990442)))
b = map(int,list(str(1313131)))
print "a :",a
print "b :",b

l= []
for p,q in zip(a,b):
    l.append(p*q)
print "prod list :",l
ls = sum(l)
print "sum :",ls
def roundup(x):
    return int(math.ceil(x / 10.0)) * 10
top = roundup(ls)
print "round value: ",top
val = top-ls
print "val :",val
a.append(val)
print "output :",a
Run Code Online (Sandbox Code Playgroud)

输出 :

a : [7, 9, 9, 0, 4, 4, 2]
b : [1, 3, 1, 3, 1, 3, 1]
prod list : [7, 27, 9, 0, 4, 12, 2]
sum : 61
round value:  70
val : 9
output : [7, 9, 9, 0, 4, 4, 2, 9]
Run Code Online (Sandbox Code Playgroud)

预期输出:

sum : 61
round value:  60
val : 1
output : [7, 9, 9, 0, 4, 4, 2, 1]
Run Code Online (Sandbox Code Playgroud)

ins*_*ant 5

您可以使用round(x / 10.0) * 10代替math.ceil.

更容易

def custom_round(x):
    return int(round(x, -1))
Run Code Online (Sandbox Code Playgroud)

这立即四舍五入到十的倍数。

  • 请注意,由于 `round` 的工作方式,此实现将产生一些可能出乎意料的结果:`custom_round(65) = 60`、`custom_round(75) = 80`。不确定这对 OP 是否重要。 (2认同)