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

标签 python rounding floor ceil

<分区>

我有一个 small task ,我将数字四舍五入为十的更高倍数。但想将其四舍五入到最接近的十的倍数。

我的代码:

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

输出:

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]

预期输出:

sum : 61
round value:  60
val : 1
output : [7, 9, 9, 0, 4, 4, 2, 1]

最佳答案

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

会更简单

def custom_round(x):
    return int(round(x, -1))

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

关于python - 如何在 python 中找到最接近的等于或大于 10 的倍数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41853155/

相关文章:

python - 如何添加来自左右的敌人?

c# - 有没有办法根据值是超过 0.5 还是低于 0.5 来确定下限/上限?

javascript - 可调整大小的二维平面图,拖动图像上的标尺

c - C 中不使用下取整函数将 float 向下舍入为整数值

python - 使用 Lambda 创建自定义 Keras Layer 对象

python - 如何同时运行多个python命令?

python - 使用 twisted.conch 跟踪 ssh 登录尝试的 IP

php - 为什么 floor(0.99999999999999999) = 1 和 floor(0.9999999999999999) = 0?

.net - 如何在 .Net 中将小数四舍五入到小数点后两位?

python - Python 中的舍入/舍入标准