Is there a built-in function that can round like this:

10 -> 10
12 -> 10
13 -> 15
14 -> 15
16 -> 15
18 -> 20

13 Answers 13

up vote 213 down vote accepted

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

def myround(x, base=5):
    return int(base * round(float(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(float(x)/5)), and then since we divided by 5, we multiply by 5 as well. The final conversion to int is because round() returns a floating-point value in Python.

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

  • 2
    If only integers and rounding down, then you can also just do x // base * base – Tjorriemorrie Dec 20 '16 at 0:59
  • 2
    this is me being paranoid but I prefer to use floor() and ceil() rather than casting: base * floor(x/base) – user666412 Apr 5 '17 at 16:06

In case someone needs "financial rounding" (0.5 rounds always up):

def myround(x, base=5):
    roundcontext = decimal.Context(rounding=decimal.ROUND_HALF_UP)
    decimal.setcontext(roundcontext)
    return int(base *float(decimal.Decimal(x/base).quantize(decimal.Decimal('0'))))

As per documentation other rounding options are:

ROUND_CEILING (towards Infinity),
ROUND_DOWN (towards zero),
ROUND_FLOOR (towards -Infinity),
ROUND_HALF_DOWN (to nearest with ties going towards zero),
ROUND_HALF_EVEN (to nearest with ties going to nearest even integer),
ROUND_HALF_UP (to nearest with ties going away from zero), or
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)

By default Python uses ROUND_HALF_EVEN as it has some statistical advantages (the rounded results are not biased).

**next multiple of 5 **

consider 51 need to converted to 55

 code here

mark=51;
r=100-mark;
a=r%5;
new_mark=mark+a;
def round_to_next5(n):
    return n + (5 - n) % 5
  • not bad, like a ceiling function – jxramos Jun 4 at 23:58

I realise I'm late to the party, but it seems that this solution has not been mentioned:

>>> from __future__ import division   # This is only needed on Python 2
>>> def round_to_nearest(n, m):
        r = n % m
        return n + m - r if r + r >= m else n - r

...

It does not use multiplication and will not convert from/to floats.

Rounding to the nearest multiple of 10:

>>> for n in range(-21, 30, 3): print('{:3d}  =>  {:3d}'.format(n, round_to_nearest(n, 10)))
-21  =>  -20
-18  =>  -20
-15  =>  -10
-12  =>  -10
 -9  =>  -10
 -6  =>  -10
 -3  =>    0
  0  =>    0
  3  =>    0
  6  =>   10
  9  =>   10
 12  =>   10
 15  =>   20
 18  =>   20
 21  =>   20
 24  =>   20
 27  =>   30

As you can see, it works for both negative and positive numbers. Ties (e.g. -15 and 15) will always be rounded upwards.

Similar example that rounds no the nearest multiple of 5, demonstrating that it also behaves as expected for a different "base":

>>> for n in range(-21, 30, 3): print('{:3d}  =>  {:3d}'.format(n, round_to_nearest(n, 5)))
-21  =>  -20
-18  =>  -20
-15  =>  -15
-12  =>  -10
 -9  =>  -10
 -6  =>   -5
 -3  =>   -5
  0  =>    0
  3  =>    5
  6  =>    5
  9  =>   10
 12  =>   10
 15  =>   15
 18  =>   20
 21  =>   20
 24  =>   25
 27  =>   25

Sorry, I wanted to comment on Alok Singhai's answer, but it won't let me due to a lack of reputation =/

Anyway, we can generalize one more step and go:

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

This allows us to use non-integer bases, like .25 or any other fractional base.

You can “trick” int() into rounding off instead of rounding down by adding 0.5 to the number you pass to int().

  • 1
    This does not actually answer the question – Uri Agassi Apr 27 '14 at 19:24

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.

  • 1
    You can use: def my_round(x, prec=2, base=0.05): return (base * (np.array(x) / base).round()).round(prec) which accepts numpy arrays as well. – saubhik May 24 at 18:21

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)
  • This only works for rounding down. – Craig Nov 10 '17 at 17:21
  • I like this answer for rounding to the nearest fractional value. i.e. If i only want increments of 0.25. – jersey bean Dec 22 '17 at 20:17

Modified version of divround :-)

def divround(value, step, barrage):
    result, rest = divmod(value, step)
    return result*step if rest < barrage else (result+1)*step
  • so in this case you use divround(value, 5, 3)? or maybe divround(value, 5, 2.5)? – pwdyson Feb 16 '10 at 13:13
  • divround(value, 5, 3), exactly. – Christian Hausknecht Feb 16 '10 at 13:18

round(x[, n]): values are rounded to the closest multiple of 10 to the power minus n. So if n is negative...

def round5(x):
    return int(round(x*2, -1)) / 2

Since 10 = 5 * 2, you can use integer division and multiplication with 2, rather than float division and multiplication with 5.0. Not that that matters much, unless you like bit shifting

def round5(x):
    return int(round(x << 1, -1)) >> 1
  • 1
    +1 for showing us that round() can handle rounding to multiples other than 1.0, including higher values. (Note, however, that the bit-shifting approach won't work with floats, not to mention it's much less readable to most programmers.) – Peter Hansen Feb 16 '10 at 14:50
  • 1
    @Peter Hansen thanks for the +1. Need to have an int(x) for the bit shifting to work with floats. Agreed not the most readable and I wouldn't use it myself, but I did like the "purity" of it only involving 1's and not 2's or 5's. – pwdyson Feb 16 '10 at 22:26

What about this:

 def divround(value, step):
     return divmod(value, step)[0] * step

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

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.