Piyush S. Wanare Piyush S. Wanare - 13 days ago 9
Python Question

Round decimal number for ratings using Python

I want to round decimal number as follows:-

n = 3.2 result n = 3
n= 3.6 result n= 4


Basically if decimal is between .0 to .4 then it should round down AND if decimal is between .5 to .9 then it should round up.

n = 3.0 result = 3
n = 3.5 result = 3.5

Answer

As I understand your use case, you should use

def r(x):
    return round(x * 2.0) / 2.0

Examples:

r(3.4) -> 3.5
r(3.24) -> 3.0
r(3.25) -> 3.5
r(3.74) -> 3.5
r(3.75) -> 4.0