Python - 四舍五入到最接近的十

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26454649/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:30:09  来源:igfitidea点击:

Python - round up to the nearest ten

pythonrounding

提问by raspberrysupreme

If I get the number 46 and I want to round up to the nearest ten. How do can I do this in python?

如果我得到数字 46 并且我想四舍五入到最接近的十。我怎么能在python中做到这一点?

46 goes to 50.

46 到 50。

采纳答案by Parker

You can use math.ceil()to round up, and then multiply by 10

您可以使用math.ceil()向上取整,然后乘以 10

import math

def roundup(x):
    return int(math.ceil(x / 10.0)) * 10

To use just do

使用只是做

>>roundup(45)
50

回答by NPE

Here is one way to do it:

这是一种方法:

>>> n = 46
>>> (n + 9) // 10 * 10
50

回答by ch3ka

rounddoes take negative ndigitsparameter!

round确实采用负ndigits参数!

>>> round(46,-1)
50

may solve your case.

可能会解决您的情况。

回答by primussucks

This will round down correctly as well:

这也将正确舍入:

>>> n = 46
>>> rem = n % 10
>>> if rem < 5:
...     n = int(n / 10) * 10
... else:
...     n = int((n + 10) / 10) * 10
...
>>> 50