How to round a float to the nearest 0.5 in Python

1 Answer

0 votes
def round_to_nearest_05(num):
    return round(num * 2) / 2

print(round_to_nearest_05(4.0)) 
print(round_to_nearest_05(4.1)) 
print(round_to_nearest_05(4.2)) 
print("  ", round_to_nearest_05(4.3))
print(round_to_nearest_05(4.4))
print(round_to_nearest_05(4.5))
print(round_to_nearest_05(4.6))
print(round_to_nearest_05(4.7))
print("  ", round_to_nearest_05(4.8))
print(round_to_nearest_05(4.9))





'''
run:
 
4.0
4.0
4.0
   4.5
4.5
4.5
4.5
4.5
   5.0
5.0

'''

 



answered Jul 15, 2022 by avibootz

Related questions

2 answers 126 views
1 answer 107 views
1 answer 103 views
...