Software Engineering

# How to Round up to the Next Multiple of 5 in Python

## The challenge#

Given an integer as input, can you round it to the next (meaning, “higher”) multiple of 5?

Examples:

``````input:    output:
0    ->   0
2    ->   5
3    ->   5
12   ->   15
21   ->   25
30   ->   30
-2   ->   0
-5   ->   -5
etc.
``````

Input may be any positive or negative integer (including 0).

You can assume that all inputs are valid integers.

## The solution in Python code#

Option 1:

``````def round_to_next5(n):
return n + (5 - n) % 5
``````

Option 2:

``````def round_to_next5(n):
while n%5!=0:
n+=1
return n
``````

Option 3:

``````import math
def round_to_next5(n):
return math.ceil(n/5.0) * 5
``````

## Test cases to validate our solution#

``````inp = 0
out = round_to_next5(inp)
test.assert_equals(out, 0, "Input: {}".format(inp))

inp = 1
out = round_to_next5(inp)
test.assert_equals(out, 5, "Input: {}".format(inp))

inp = -1
out = round_to_next5(inp)
test.assert_equals(out, 0, "Input: {}".format(inp))

inp = 5
out = round_to_next5(inp)
test.assert_equals(out, 5, "Input: {}".format(inp))

inp = 7
out = round_to_next5(inp)
test.assert_equals(out, 10, "Input: {}".format(inp))

inp = 20
out = round_to_next5(inp)
test.assert_equals(out, 20, "Input: {}".format(inp))

inp = 39
out = round_to_next5(inp)
test.assert_equals(out, 40, "Input: {}".format(inp))
``````