Python 最接近的值数字



我想将值四舍五入到最接近的 10(0-4 = 0; 5-14 = 1; 15-24=2,依此类推)我可以四舍五入到最接近的 10,但我想为每个数字范围使用个位数,如示例所示。

从 -5 到 4 = 0,5 到 14 = 1,15 到 24 = 2 等等...

我试过什么...

int(math.ceil(x / 10.0)) * 10
这给出了最接近的 10,

但从 0 开始,给出最接近的 10 而不是个位数。

任何建议都是有帮助的。

我们可以

简单地使用:

int(round(float(x)/10))

documentation

round(number[, ndigits])

返回四舍五入到小数点后 n 位数字的浮点值数字。如果省略 ndigits,则默认为零。结果是一个浮点数。值四舍五入到最接近的 10 的倍数,以减去 n 位数;如果两个倍数同样接近,则舍入远离 0(因此,例如,round(0.5) 为 1.0,round(-0.5) 为 -1.0)。

最新更新