Python - Rounding by quarter-intervals

Daniyal picture Daniyal · Nov 14, 2011 · Viewed 7.6k times · Source

I'm running into the following issue:

Given various numbers like:

10.38

11.12

5.24

9.76

does an already 'built-in' function exists to round them up to the closest 0.25 step like e.g.:

10.38 --> 10.50

11.12 --> 11.00

5.24 --> 5.25

9.76 --> 9-75 ?

Or can I go ahead and hack together a function that performs the desired task?

Thanks in advance and

with best regards

Dan

Answer

rytis picture rytis · Nov 14, 2011
>>> def my_round(x):
...  return round(x*4)/4
... 
>>> 
>>> assert my_round(10.38) == 10.50
>>> assert my_round(11.12) == 11.00
>>> assert my_round(5.24) == 5.25
>>> assert my_round(9.76) == 9.75
>>>