+ 1
How do you round to the nearest whole number in python?!
4 Answers
+ 10
use round()
+ 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()
+ 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))
+ 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