round off float to nearest 0.5 in python [duplicate]
Try to change the parenthesis position so that the rounding happens before the division by 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
Edit: Added a doctest
able docstring:
>>> import doctest
>>> doctest.testmod()
TestResults(failed=0, attempted=4)