1

I have been trying to round of any number to the nearest multiple of 5. By saying that, I mean that it should always round up. However, my piece of code is always to rounding off to the nearest multiple of 5 either up or down depending on the number I input. The numbers are always int and whole numbers. Here's my code:

num = int(input())
base = 5
for x in range(num):
    number = int(input())
    round_off = base * round(number/base)
    print(round_off)

The input and output:

in:4
in:73
out:75 #correct
in:67
out:65 #wrong, should be 70
in:38
out:40 #correct
in:33
out:35 #correct

As you can see, only 67 and probably others similar to that(like 57) will give me the wrong output. How can I fix my code to get the correct output?

Mahir Islam
  • 1,941
  • 2
  • 12
  • 33

2 Answers2

1

You need to always round up:

import math
round_off = base * math.ceil(number / base)
N Chauhan
  • 3,407
  • 2
  • 7
  • 21
0

If you always want to round up, you can:

num = int(input())
if num % 5 != 0:
  num += 5
  num -= (num % 5)

If you want a one liner:

num = num if num % 5 == 0 else num + 5 - (num % 5)

Note: Both example work with a generic integral base value instead of 5:

num = num if num % base == 0 else num + base - (base % 5)
Daniel Trugman
  • 8,186
  • 20
  • 41