Python – round up to the nearest ten

Question:

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.

Asked By: raspberrysupreme

||

Answers:

Here is one way to do it:

>>> n = 46
>>> (n + 9) // 10 * 10
50
Answered By: NPE

round does take negative ndigits parameter!

>>> round(46,-1)
50

may solve your case.

Answered By: ch3ka

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
Answered By: Parker

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
Answered By: primussucks
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.