0

I want to round numbers down to the next 5 in python
What I mean:

1 -> 0
3 -> 0
4 -> 0
5 -> 5
7 -> 5
9 -> 5
...

I already searched a lot for rounding numbers with a base but then also 3 -> 5 but it has to be 3 -> 0

Thank you for helping me with this

chraebsli
  • 184
  • 12

3 Answers3

4

Simply subtract the remainder of the integer division by 5:

n - n % 5 
Sirion
  • 804
  • 1
  • 11
  • 33
2

If you're on Python 2:

def func(n):
    return (n / 5) * 5

If you're on Python 3:

def func(n):
    return (n // 5) * 5
1

Less hacky / more Pythonian to use math.floor, like this:

from math import floor

def floor5(x):
  return floor(x/5)*5

# Test:
print(list(map(floor5, [1, 3, 4, 5, 7, 9])))

Output

[0, 0, 0, 5, 5, 5]
user23952
  • 578
  • 3
  • 10