Python - Rounding by quarter-intervals

前端 未结 4 915
别跟我提以往
别跟我提以往 2020-12-10 11:08

I\'m running into the following issue:

Given various numbers like:

10.38

11.12

5.24

9.76

does an already \'built-in\' functio

4条回答
  •  渐次进展
    2020-12-10 12:06

    This is a general purpose solution which allows rounding to arbitrary resolutions. For your specific case, you just need to provide 0.25 as the resolution but other values are possible, as shown in the test cases.

    def roundPartial (value, resolution):
        return round (value / resolution) * resolution
    
    print "Rounding to quarters"
    print roundPartial (10.38, 0.25)
    print roundPartial (11.12, 0.25)
    print roundPartial (5.24, 0.25)
    print roundPartial (9.76, 0.25)
    
    print "Rounding to tenths"
    print roundPartial (9.74, 0.1)
    print roundPartial (9.75, 0.1)
    print roundPartial (9.76, 0.1)
    
    print "Rounding to hundreds"
    print roundPartial (987654321, 100)
    

    This outputs:

    Rounding to quarters
    10.5
    11.0
    5.25
    9.75
    Rounding to tenths
    9.7
    9.8
    9.8
    Rounding to hundreds
    987654300.0
    

提交回复
热议问题