0

How do I round a number to the nearest whole in Python

15th Jul 2021, 10:01 PM
Johanan Oppong Amoateng
Johanan Oppong Amoateng - avatar
4 Réponses
+ 3
round(4.51) >>> 5
16th Jul 2021, 12:10 AM
Solo
Solo - avatar
+ 1
You can also use string formatting to automatically round a float for you. To round to the nearest whole number use :.0f x = 4.6 print(f"{x:.0f}") # 5
16th Jul 2021, 3:58 AM
ChaoticDawg
ChaoticDawg - avatar
0
Take note of the difference between python round and other programming languages. See: https://www.sololearn.com/post/876419/?ref=app If you want it to work like the others, do this: from math import floor myRound = lambda x: floor(x + 0.5)
17th Jul 2021, 9:24 PM
Louis
Louis - avatar
- 1
Maybe convert to integer int(4.675) --> 4
15th Jul 2021, 10:51 PM
blackfish
blackfish - avatar