Python - round up to the nearest ten [duplicate]

℡╲_俬逩灬. 提交于 2019-12-18 04:28:13

问题


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 goes to 50.


回答1:


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

import math

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

To use just do

>>roundup(45)
50



回答2:


round does take negative ndigits parameter!

>>> round(46,-1)
50

may solve your case.




回答3:


Here is one way to do it:

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



回答4:


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


来源:https://stackoverflow.com/questions/26454649/python-round-up-to-the-nearest-ten

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!