在python中将float浮动到最接近的0.5

Yin*_*ang 39 python

我试图将浮动数字四舍五入到最接近的0.5

例如.

1.3 -> 1.5
2.6 -> 2.5
3.0 -> 3.0
4.1 -> 4.0
Run Code Online (Sandbox Code Playgroud)

这就是我正在做的事情

def round_of_rating(number):
        return round((number * 2) / 2)
Run Code Online (Sandbox Code Playgroud)

这轮数字到最接近的整数.这样做的正确方法是什么?

fae*_*ter 66

尝试更改括号位置,以便在除以2之前进行舍入

def round_of_rating(number):
    """Round a number to the closest half integer.
    >>> round_of_rating(1.3)
    1.5
    >>> round_of_rating(2.6)
    2.5
    >>> round_of_rating(3.0)
    3.0
    >>> round_of_rating(4.1)
    4.0"""

    return round(number * 2) / 2
Run Code Online (Sandbox Code Playgroud)

编辑:添加了一个doctest能够的文档字符串:

>>> import doctest
>>> doctest.testmod()
TestResults(failed=0, attempted=4)
Run Code Online (Sandbox Code Playgroud)

  • 我不得不说`/ 2`让我对意外使用地板分区感到紧张,但事实证明它在Python 2和Python 3中都没问题(出于不同的原因):在Python 2中,`round`返回浮点数甚至对于整数输入,在Python 3中,`/`执行真正的除法而不是地板划分!尽管如此,我仍然可能会使用"2.0"来保存代码的读者不必进行相同的心理检查. (4认同)
  • 顺便说一句,这个数字是通用的.您可以通过将2更改为其他数字来找到最接近的第三,第四,第五等.但要注意获取无理数. (2认同)