round off float to nearest 0.5 in python
Question:
I’m trying to round off floating digits to the nearest 0.5
For eg.
1.3 -> 1.5
2.6 -> 2.5
3.0 -> 3.0
4.1 -> 4.0
This is what I’m doing
def round_of_rating(number):
return round((number * 2) / 2)
This rounds of numbers to closest integer. What would be the correct way to do this?
Answers:
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)
I’m trying to round off floating digits to the nearest 0.5
For eg.
1.3 -> 1.5
2.6 -> 2.5
3.0 -> 3.0
4.1 -> 4.0
This is what I’m doing
def round_of_rating(number):
return round((number * 2) / 2)
This rounds of numbers to closest integer. What would be the correct way to do this?
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)