Home > Blockchain >  how to round up to a multiple of 30 in python?
how to round up to a multiple of 30 in python?

Time:03-15

I need to round the user input up to the next 30, for example if the number entered was 27 I would need the output to be 30. or if they entered 33 the output would need to be 60. I don't even know where to start with this.

like this:

15-->30

1-->30

35-->60

56-->60

61-->90

43-->60

and so on with any input.

CodePudding user response:

You can use math.ceil like this:

int(math.ceil(yourNum / 30.0)) * 30

That is, rounding up the division of your number by 30, and then multiplying by 30.

CodePudding user response:

number = 35

# Integer division of the number by 30, add 1 and multiply by 30:
result = ((number - 1) // 30   1) * 30

CodePudding user response:

This works:

import math


def round_next_multiple_of_30(input_number: int) -> int:
    return math.ceil(input_number / 30.0) * 30


assert round_next_multiple_of_30(15) == 30
assert round_next_multiple_of_30(1) == 30
assert round_next_multiple_of_30(35) == 60
assert round_next_multiple_of_30(61) == 90

CodePudding user response:

The next function may be use to round up to any base:

import math

def myround(x, base=30):
    return base * math.ceil(x/base)

CodePudding user response:

I would suggest to divide by 30, use math.ceil() to round up to the nearest integer, and multiply by 30 again:

import math
rounded_number = (math.ceil(unrounded_number / 30)) * 30

CodePudding user response:

Here is my solution:

import math

def next30(num):
    return math.ceil(num / 30.0) * 30

number = float(input("Number: "))
print(next30(number))
  • Related