How to round number to 10, 100, 1000, 10000, 100000

Question:

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

Asked By: Matt Cao

||

Answers:

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))

Another option (without math):

def roundup(n):
    return 10**(len(str(n))-1)
Answered By: Tarifazo

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.

Answered By: Serge Ballesta
def roundup(n):
    if n < 0:
        return 0
    size = len(str(n))
    return int('1'.ljust(size+1, '0'))
Answered By: Victor Outtes
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.