Python - 舍入到最接近的05

pkd*_*dkk 13 python rounding

我可以蟒蛇做以下四舍五入:

舍入到最接近的05十进制数

7,97 - > 7,95

6,72 - > 6,70

31,06 - > 31,05

36,04 - > 36,05

5,25 - > 5,25

希望它有意义.

for*_*ran 26

def round_to(n, precision):
    correction = 0.5 if n >= 0 else -0.5
    return int( n/precision+correction ) * precision

def round_to_05(n):
    return round_to(n, 0.05)
Run Code Online (Sandbox Code Playgroud)


Dav*_*ebb 12

def round05(number):
    return (round(number * 20) / 20)
Run Code Online (Sandbox Code Playgroud)

或者更一般地说:

def round_to_value(number,roundto):
    return (round(number / roundto) * roundto)
Run Code Online (Sandbox Code Playgroud)

唯一的问题是因为你使用花车你不会得到你想要的答案:

>>> round_to_value(36.04,0.05)
36.050000000000004
Run Code Online (Sandbox Code Playgroud)