-1

I want a function that will round the number to 10 if it is less than 10, round to 100 if it is between 10 to 1000 and so on.

this will help number concatenation problems, so I don't have to turn number to str and back.

def roundup(n):
    if n < 0: return 0
    if n < 10: return 10
    if n < 100: return 100
    if n < 1000: return 1000
    if n < 10000: return 10000

I want to know if there is a natural way to do this without just stacking 'if's together

user2357112
  • 260,549
  • 28
  • 431
  • 505
Matt Cao
  • 63
  • 1
  • 6
  • 5
    Possible duplicate of [Rounding to a power of 10](https://stackoverflow.com/questions/6769406/rounding-to-a-power-of-10). Actually this is the wrong dupe target, but the logic is the same. (`10**floor(log10(x))`) – pault Jan 09 '19 at 16:34
  • Yes, you are right. but i got the answer I want here, a naive python way – Matt Cao Jan 09 '19 at 16:57

4 Answers4

6

This is more of a math problem than a python specific problem but you are effectively taking a floor of the log of a number.

def round_base_10(x):
    if x < 0:
        return 0
    elif x == 0:
        return 10
    return 10**math.ceil(math.log10(x))
Gerges
  • 6,269
  • 2
  • 22
  • 44
Victor 'Chris' Cabral
  • 2,135
  • 1
  • 16
  • 33
0

Another option (without math):

def roundup(n):
    return 10**(len(str(n))-1)
Tarifazo
  • 4,118
  • 1
  • 9
  • 22
0

You could use the naive approach:

def roundup(n):
    top = 1
    while True:
        if n <= top:
            return top
        top *= 10

You would need top = 1L in Python2, but integers are long by default in Python3.

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
0
def roundup(n):
    if n < 0:
        return 0
    size = len(str(n))
    return int('1'.ljust(size+1, '0'))