将整数四舍五入到最接近的 10 [英] Round integers to the nearest 10

查看:51
本文介绍了将整数四舍五入到最接近的 10的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 python 中舍入整数.我查看了内置的 round() 函数,但似乎 rounds 是浮动的.

我的目标是将整数四舍五入到最接近的 10 倍数.即:5-> 10、4-> 0、95->100 等

5 及更高应向上舍入,4 及更低应向下舍入.

这是我的代码:

def round_int(x):last_dig = int(str(x)[-1])如果 last_dig >= 5:x += 10返回 (x/10) * 10

这是实现我想要实现的目标的最佳方式吗?有没有内置函数可以做到这一点?另外,如果这是最好的方法,我在测试中遗漏的代码有什么问题吗?

解决方案

其实你还是可以用round函数的:

<预><代码>>>>打印轮(1123.456789,-1)1120.0

这将四舍五入到最接近的 10 的倍数.到 100 将是 -2 作为第二个参数,依此类推.

I am trying to round integers in python. I looked at the built-in round() function but it seems that that rounds floats.

My goal is to round integers to the closest multiple of 10. i.e.: 5-> 10, 4-> 0, 95->100, etc.

5 and higher should round up, 4 and lower should round down.

This is the code I have that does this:

def round_int(x):
    last_dig = int(str(x)[-1])
    if last_dig >= 5:
        x += 10
    return (x/10) * 10

Is this the best way to achieve what I want to achieve? Is there a built-in function that does this? Additionally, if this is the best way, is there anything wrong with the code that I missed in testing?

解决方案

Actually, you could still use the round function:

>>> print round(1123.456789, -1)
1120.0

This would round to the closest multiple of 10. To 100 would be -2 as the second argument and so forth.

这篇关于将整数四舍五入到最接近的 10的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆