Python - Round to nearest 05

后端 未结 9 1922
死守一世寂寞
死守一世寂寞 2020-11-29 08:14

Hvor can I en python do the following rounding:

Round to the nearest 05 decimal

7,97 -> 7,95

6,72 -> 6,70

31,06 -> 31,05

36,04 -> 36,

9条回答
  •  再見小時候
    2020-11-29 09:11

    def round05(number):
        return (round(number * 20) / 20)
    

    Or more generically:

    def round_to_value(number,roundto):
        return (round(number / roundto) * roundto)
    

    The only problem is because you're using floats you won't get exactly the answers you want:

    >>> round_to_value(36.04,0.05)
    36.050000000000004
    

提交回复
热议问题