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?

Asked By: Yin Yang

||

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)
Answered By: faester
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.