在Python中将浮点数四舍五入到最近的0.5

61 投票
1 回答
83167 浏览
提问于 2025-04-18 13:56

我想把小数四舍五入到最接近的0.5。

比如说:

1.3 -> 1.5
2.6 -> 2.5
3.0 -> 3.0
4.1 -> 4.0

这是我现在的做法:

def round_of_rating(number):
        return round((number * 2) / 2)

这个方法是把数字四舍五入到最接近的整数。那么,正确的做法应该是什么呢?

1 个回答

114

试着改变括号的位置,让四舍五入的操作在除以2之前进行。

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

    return round(number * 2) / 2

编辑:添加了一个可以用doctest测试的文档字符串:

>>> import doctest
>>> doctest.testmod()
TestResults(failed=0, attempted=4)

撰写回答