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?
This comes from the Median work where the first print produces, say a value of 5 then after being divided by 2 and calling int it becomes 2.
If you want to round up, use math. ceil . @Thom "round" means go to the nearest. Use floor or ceil to go down or up always.
Round() Round() is a built-in function available with python. It will return you a float number that will be rounded to the decimal places which are given as input. If the decimal places to be rounded are not specified, it is considered as 0, and it will round to the nearest integer.
Round() function in Python follows the half to even rounding strategy. In this strategy, the number is rounded off to its nearest even integer. For example, if we need to round off 7.5, it will be rounded off to its nearest even integer that is 8.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With