Search code examples
pythonmathrounding

Round up to the nearest 0.05


I want to round up a number to 2 decimals, for example:

16.34 -> 16.35
16.36 -> 16.40
16.31 -> 16.35
16.35 -> 16.35 -- NOT ROUND
16.40 -> 16.40 -- NOT ROUND

If the number ended in 1-4 round to 5 and if the number 6-9 then round up to 0 How i can round up= Thanks u


Solution

  • Multiply the number by 20 (the reciprocal of 0.05), round up with math.ceil, and divide by the reciprocal.

    For example:

    >>> from math import ceil
    >>> r = 0.05 ** -1
    >>> for n in (i/100 for i in range(10, 20)):
    ...     m = ceil(n*r) / r
    ...     print('{:.2f} -> {:.2f}'.format(n, m))
    ...
    0.10 -> 0.10
    0.11 -> 0.15
    0.12 -> 0.15
    0.13 -> 0.15
    0.14 -> 0.15
    0.15 -> 0.15
    0.16 -> 0.20
    0.17 -> 0.20
    0.18 -> 0.20
    0.19 -> 0.20
    

    [Due credit to Jan Stránský's and Thomas Jager's comments for explaining the technique]

    Edit: Revisiting this, I think it's equivalent to a) use 0.05 itself instead of its reciprocal, reversing the operations, and b) use negative floor division instead of ceil.

    >>> r = 0.05
    >>> for n in (i/100 for i in range(10, 20)):
    ...     m = n // -r * -r
    ...     print('{:.2f} -> {:.2f}'.format(n, m))
    ... 
    

    (same output)