pythonrounding

Rounding Rules in Python


I am trying to round to some different rules within python. For example;

10.666 = 10.6
10.667 = 10.7

ie down on 6, and up on 7.

Is there a way that I can do this with Python?


Solution

  • I'm not sure exactly what sort of rounding rules you have in mind. Can you give more detail on your rounding rules?

    Therefore I can't say this is exactly right, but I suspect you could use it as a pattern for your implementation.

    def cround(v):
        """
        Round number down at 1st decimal place when the digit in the 
        3rd decimal place is <= 6, up when >= 7
        """
        v *= 10
        q = str(round(v, 2))
        if int(q[-1]) <= 6:
            return int(v) / 10.0
        return round(v) / 10.0
    
    NUMS = [
        10.666, 10.667, 0.1, 1.0, 10.11, 10.22, 10.06, 10.006, 11.6, 11.7,
        10.666123, 10.667123, 10.888, 10.999 ]
    
    for num in NUMS:
        print str(num).ljust(11), cround(num)
    

    Output:

    10.666      10.6
    10.667      10.7
    0.1         0.1
    1.0         1.0
    10.11       10.1
    10.22       10.2
    10.06       10.0
    10.006      10.0
    11.6        11.6
    11.7        11.7
    10.666123   10.6
    10.667123   10.7
    10.888      10.9
    10.999      11.0