[Python] Function for rounding up

Discussão em 'Python' iniciado por Stack, Abril 11, 2025.

  1. Stack

    Stack Membro Participativo

    I am currently learning Python and is answering some online questions. the question is to write a Python function to round up a number to specified digits.

    My answer is completely different from the solution provided. Can someone explain to me the difference? And which solutions if more efficient?

    I am asking so i can improve how i write scripts

    My Script:

    import math

    number = float(input("Provide a number: "))
    factor = float(input("rounding factor: "))

    def round_up(number, factor):
    return math.ceil(number / factor) * factor

    result = round_up(number, factor)
    print(result)


    Solution script:

    import math

    def roundup(a, digits=0):
    n = 10**-digits
    return round(math.ceil(a / n) * n, digits)

    x = 123.01247
    print("Original Number: ",x)
    print(roundup(x, 0))
    print(roundup(x, 1))
    print(roundup(x, 2))
    print(roundup(x, 3))

    Continue reading...

Compartilhe esta Página