73

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.

raspberrysupreme
  • 949
  • 2
  • 9
  • 11

4 Answers4

184

round does take negative ndigits parameter!

>>> round(46,-1)
50

may solve your case.

ch3ka
  • 11,792
  • 4
  • 31
  • 28
91

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

Python 2

import math

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

Python 3 (the only difference is you no longer need to cast the result as an int)

import math

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

To use just do

>>roundup(45)
50
Parker
  • 8,539
  • 10
  • 69
  • 98
  • That does not work always: If `x = 1000000000000000010` then `print(int(math.ceil(x / 10.0)) * 10)` outputs `1000000000000000000`. – Jaakko Seppälä Nov 13 '17 at 18:55
  • 3
    I think that's because you're going past the python int limit – Parker Dec 11 '17 at 01:09
  • As far as I know, there is no longer a limit on the maximum size of an integer in Python, see here: https://www.daniweb.com/programming/software-development/threads/71008/comparing-python-and-c-part-1-integer-variables – Martin Hepp Nov 07 '19 at 19:45
  • It is more likely because you hit the `eps` and finite precision take over after that. – sotmot Dec 18 '21 at 15:29
  • 1
    The expression `math.ceil(x / 10) * 10` works just fine. No need for those conversions in recent versions of Python. – Jeyekomon Feb 08 '22 at 12:52
26

Here is one way to do it:

>>> n = 46
>>> (n + 9) // 10 * 10
50
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • 5
    Nice trick. Boils down to adding the numbers base minus 1. – Mads Y Dec 05 '15 at 16:45
  • 2
    this would fail for numbers like 0.5 or 30.5 and so on (i.e. k*10+a where k is an integer and 0 < a < 1 ) – epeleg Oct 03 '17 at 09:52
  • 3
    yes the answer assumes the input in an integer only - not clear from the question that this was a condition, although the example implies this is the case – ClimateUnboxed Oct 09 '18 at 01:58
16

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
Community
  • 1
  • 1
primussucks
  • 293
  • 2
  • 5