Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round to 5 (or other number) in Python

People also ask

How do you round a number to the nearest 5 in Python?

ROUND_HALF_UP (to nearest with ties going away from zero) ROUND_UP (away from zero) ROUND_05UP (away from zero if last digit after rounding towards zero would have been 0 or 5; otherwise towards zero)

How do you round to a specific number in Python?

Python has a built-in round() function that takes two numeric arguments, n and ndigits , and returns the number n rounded to ndigits . The ndigits argument defaults to zero, so leaving it out results in a number rounded to an integer.

How do you round a number to multiple in Python?

The Quick Answer: Use multiple * (number / multiple) Developing a Custom Function to Round to a Multiple in Python (e.g., 2, 5, etc.)

What does 0.5 round to Python?

Values are rounded to the closest multiple of 10 to the power minus decimalplaces; if two multiples are equally close, rounding is done away from 0 (so. for example, round(0.5) is 1.0 and round(-0.5) is -1.0).


I don't know of a standard function in Python, but this works for me:

Python 3

def myround(x, base=5):
    return base * round(x/base)

It is easy to see why the above works. You want to make sure that your number divided by 5 is an integer, correctly rounded. So, we first do exactly that (round(x/5)), and then since we divided by 5, we multiply by 5 as well.

I made the function more generic by giving it a base parameter, defaulting to 5.

Python 2

In Python 2, float(x) would be needed to ensure that / does floating-point division, and a final conversion to int is needed because round() returns a floating-point value in Python 2.

def myround(x, base=5):
    return int(base * round(float(x)/base))

For rounding to non-integer values, such as 0.05:

def myround(x, prec=2, base=.05):
  return round(base * round(float(x)/base),prec)

I found this useful since I could just do a search and replace in my code to change "round(" to "myround(", without having to change the parameter values.


It's just a matter of scaling

>>> a=[10,11,12,13,14,15,16,17,18,19,20]
>>> for b in a:
...     int(round(b/5.0)*5.0)
... 
10
10
10
15
15
15
15
15
20
20
20

Removing the 'rest' would work:

rounded = int(val) - int(val) % 5

If the value is aready an integer:

rounded = val - val % 5

As a function:

def roundint(value, base=5):
    return int(value) - int(value) % int(base)

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