0

How can we round off a float value to the nearest integer in python?

4th Sep 2020, 8:57 AM
Anirudh Rameshan
Anirudh Rameshan - avatar
8 Respostas
+ 4
my recommendation: don't use any function use like this: if(21%2==0): print(21//2) else: print((21//2)+1) adding 1 is best way for knowledge if division gives float add one
4th Sep 2020, 9:06 AM
Rajababu Shah
+ 4
Your last code IS the best method (that I know)
4th Sep 2020, 11:11 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 3
import math print(math.ceil(21/2)) mc = math.ceil print(mc(33/4))
4th Sep 2020, 9:56 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 3
Your code will round down, or round up depending on your decimals. Your question indicates that you want all decimal results to round up. Can you clarify exactly what you are trying to achieve
4th Sep 2020, 10:48 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 2
Let me clarify my doubt: the user inputs a positive integer which is to be divided by another positive integer. The quotient should be rounded off to the nearest integer. Eg. 200/3=66.666...=~67
4th Sep 2020, 9:47 AM
Anirudh Rameshan
Anirudh Rameshan - avatar
+ 2
Here's how I solved it: divd = int(input()) divs = int(input()) quo = divd/divs rem = quo%1 ans = int(quo) if rem<0.5: print(ans) elif rem==0.5: if ans%2==0: print(ans) else: print(ans+1) else: print(ans+1)
4th Sep 2020, 10:03 AM
Anirudh Rameshan
Anirudh Rameshan - avatar
+ 2
Found a direct method: divd = int(input()) divs = int(input()) quo = divd/divs print(round(quo))
4th Sep 2020, 11:05 AM
Anirudh Rameshan
Anirudh Rameshan - avatar
+ 1
Rik Wittkopp Edited👍 I wanted to round off
4th Sep 2020, 11:09 AM
Anirudh Rameshan
Anirudh Rameshan - avatar