pythonpython-2.7odooodoo-10

Need to round in multiples of 0.25


I need to round the currency amount in 0.25, 0.50, 0.75 and if greater than 0.75, it must round to the next integer.

How to do it?

Example need to round:

and so on.


Solution

  • If you want to round to the next highest quarter, you can use math.ceil().

    >>> import math
    >>> def quarter(x):
    ...     return math.ceil(x*4)/4
    ...
    >>> quarter(25.91)
    26.0
    >>> quarter(25.21)
    25.25
    >>> quarter(25.44)
    25.5
    

    If you want to round to the closest quarter instead of the next highest, just replace math.ceil with round:

    >>> def nearest_quarter(x):
    ...     return round(x*4)/4
    ...
    >>> nearest_quarter(4.51)
    4.5