我试图将浮动数字四舍五入到最接近的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)
这轮数字到最接近的整数。这样做的正确方法是什么?
答案 0 :(得分:58)
尝试更改括号位置,以便在除法之前进行舍入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
编辑:添加了doctest
文件字符串:
>>> import doctest
>>> doctest.testmod()
TestResults(failed=0, attempted=4)