round off float to nearest 0.5 in python

Python

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYin YangView Question on Stackoverflow
Solution 1 - PythonfaesterView Answer on Stackoverflow