How to round of a float to a nearest whole number? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

How to round of a float to a nearest whole number?

Languege used: Python

6th May 2022, 1:33 PM
Tan Jing Xuan
Tan Jing Xuan - avatar
15 Answers
+ 4
round(yourNumber,0) the type of the returned number is float if you want it as integer you can use int( round(yourNumber,0))
6th May 2022, 1:42 PM
Zakaria Elalaoui
Zakaria Elalaoui - avatar
+ 3
x = round(5.5, 0) still a float, but rounded to the nearest whole number.
6th May 2022, 1:39 PM
Bob_Li
Bob_Li - avatar
+ 3
x = round(5.5,) if you want int
6th May 2022, 1:41 PM
Bob_Li
Bob_Li - avatar
+ 3
#round(number,n) -> n represents number of digits to after decimal point x = 2.527 print(x) print(round(x,0), round(x,1), round(x,2))
6th May 2022, 1:59 PM
Jayakrishna 🇮🇳
+ 2
rounding does not always show the expected result. print(round(3.00014,3)) will result in 3.0 this is since the 3 first digital places of the number are 0. in this case only 1 decimal place will be displayed.
6th May 2022, 2:31 PM
Lothar
Lothar - avatar
+ 1
what programming language?
6th May 2022, 1:34 PM
Bob_Li
Bob_Li - avatar
+ 1
Here is a function that I wrote for rounding float numbers def round(num): newNum = num - int(num) if newNum >= 0.5: num += 1 num = int(num) return num num = int(num) return num
6th May 2022, 1:43 PM
Mohammad Matin Kateb
Mohammad Matin Kateb - avatar
+ 1
x = 5.5 print(f'{x:.0f}') if you only want to round when printed.
6th May 2022, 1:46 PM
Bob_Li
Bob_Li - avatar
+ 1
Tan Jing Xuan the second argument is used to specify how many decimal places you want the result to be. You can replace it with any whole number.
6th May 2022, 1:56 PM
Bob_Li
Bob_Li - avatar
+ 1
ravilnicki Mohammad Matin Kateb You are right.😅 I keep forgetting this part where if you don't give a second argument, it will round to int.
6th May 2022, 1:59 PM
Bob_Li
Bob_Li - avatar
+ 1
Use round() bro Or math.ceil, but you will need to import math module Like this import math whole=(math.ceil(12.45))
7th May 2022, 3:26 PM
MIKEY
MIKEY - avatar
0
What does 0 in round function stand for?
6th May 2022, 1:43 PM
Tan Jing Xuan
Tan Jing Xuan - avatar
0
Rounding is not a simple matter, specially if you are dealing with a lot of values. And there are a lot of rounding methods. Further reading: https://realpython.com/JUMP_LINK__&&__python__&&__JUMP_LINK-rounding/#:~:text=Python%20has%20a%20built%2Din,number%20rounded%20to%20an%20integer.
6th May 2022, 2:23 PM
Bob_Li
Bob_Li - avatar
0
You can use the round function in the python language
7th May 2022, 5:46 PM
Pv Sarath
0
math ka cli if your want whole number
8th May 2022, 9:44 AM
TeenX
TeenX - avatar