Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

round off float to nearest 0.5 in python [duplicate]

Tags:

python

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?

like image 224
Yin Yang Avatar asked Jul 19 '14 09:07

Yin Yang


People also ask

Why is .5 rounded down Python?

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.

How do you round to the nearest 0.25 in Python?

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.

How do you round to the nearest float in Python?

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.

What is round 7.5 in Python?

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.


1 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 doctestable docstring:

>>> import doctest >>> doctest.testmod() TestResults(failed=0, attempted=4) 
like image 106
faester Avatar answered Oct 14 '22 16:10

faester