+ 1

How do you round to the nearest whole number in python?!

11th Jan 2021, 2:37 PM
keorapetse Moagi
keorapetse Moagi - avatar
4 Réponses
+ 10
use round()
11th Jan 2021, 2:39 PM
Steven Wen
Steven Wen - avatar
+ 8
keorapetse Moagi , it depends what exactly is mentioned in the task description. When it says: <... rounded up to the nearest whole number>, you should use math.ceil(). this is working like this: from math import ceil a = 5.01 b = 5.99 print(ceil(a)) # result is 6 print(ceil(b)) # result is 6 for rounding down you can use floor()
11th Jan 2021, 3:34 PM
Lothar
Lothar - avatar
+ 6
# this is how round method works, mentioned by Steven Wen import math a = 5.4 if (a-int(a) >= 0.5): print(math.ceil(a)) else: print(math.floor(a)) # OR without math imported a = 5.4 if (a-int(a) >= 0.5): print(int(a)+1) else: print(int(a))
11th Jan 2021, 3:07 PM
minirkk
minirkk - avatar
+ 3
The built in round fuction in python does not work the same as most other programming languages. It rounds to the closest even number, for more info see here. https://www.sololearn.com/post/876419/?ref=app What you need for normal rounding is this. from math import floor myRound = lambda x: floor(x + 0.5) Or see this https://code.sololearn.com/cqVni1zIehbo/?ref=app
12th Jan 2021, 6:20 AM
Louis
Louis - avatar