Python - round up to the nearest ten

PythonRounding

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

round does take negative ndigits parameter!

>>> round(46,-1)
50

may solve your case.

Solution 2 - Python

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

Solution 3 - Python

Here is one way to do it:

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

Solution 4 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionraspberrysupremeView Question on Stackoverflow
Solution 1 - Pythonch3kaView Answer on Stackoverflow
Solution 2 - PythonParkerView Answer on Stackoverflow
Solution 3 - PythonNPEView Answer on Stackoverflow
Solution 4 - PythonprimussucksView Answer on Stackoverflow