pythonroundingintervals

Python - Rounding by quarter-intervals


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 exist 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?


Solution

  • >>> 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
    >>>