61

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?

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
Yin Yang
  • 1,776
  • 3
  • 26
  • 48

1 Answers1

112

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)
boxed
  • 3,895
  • 2
  • 24
  • 26
faester
  • 14,886
  • 5
  • 45
  • 56
  • 4
    I have to say that the `/ 2` makes me nervous about accidentally using floor division, but it turns out that it's okay (for different reasons) in both Python 2 and Python 3: in Python 2, `round` returns a float even for integer input, and in Python 3, `/` does true division rather than floor division! Nevertheless, I'd still probably use a `2.0` to save readers of the code from having to go through the same mental checks. – Mark Dickinson Jul 19 '14 at 10:04
  • 2
    BTW, the number is generalisable. You can find the closest third, fourth, fifth.. etc just by changing the 2 to some other number. But beware of acquiring irrational numbers. – CMCDragonkai Sep 29 '15 at 14:31