+ 2

How to round a number to the nearest integer in python?

In JavaScript I often use math.round(), but what is its equivalent in python?

13th Aug 2024, 11:17 AM
[ Laur€nt ]
14 Antworten
+ 8
It's `round()` in python. Example:- print(round(5.8)) print(round(5.3))
13th Aug 2024, 11:40 AM
Gulshan Mahawar
Gulshan Mahawar - avatar
+ 5
[ Laur€nt ] , in python there is no such function. to get it done, we can use an f-string like this: val = 42.1 print(f'{val:.2f}') # for more details have a look at the python docs result is: 42.10
13th Aug 2024, 12:42 PM
Lothar
Lothar - avatar
+ 4
I would not suggest using the round() method to get the nearest integer, it is because the round() method uses banker's rounds, which can give an expected (for normal use) result. For example: round(2.5) # 2 round(2.5, 0) # 2.0 This post has info about that issue. To get the desired rounding, we can use the decimal module, and change the rounding method. If you are not comfortable with that, you can make your own method. To use the above example. def my_rounding(num): '''It only handles positive integer''' q, r = divmod(num, 1) if r >= 0.5: return int(q + 1) else: return (q) print(my_rounding(2.5)) # 3 print(my_rounding(2.4)) # 2 https://www.sololearn.com/discuss/3284453/?ref=app
13th Aug 2024, 12:58 PM
Wong Hei Ming
Wong Hei Ming - avatar
14th Aug 2024, 12:29 PM
Louis
Louis - avatar
+ 2
Gulshan Mahawar Wong Hei Ming Lothar Thank you, thanks to you I was able to solve my coach code(⁠づ⁠。⁠◕⁠‿⁠‿⁠◕⁠。⁠)⁠づ༼⁠ ⁠つ⁠ ⁠◕⁠‿⁠◕⁠ ⁠༽⁠つ
13th Aug 2024, 1:01 PM
[ Laur€nt ]
+ 2
***JUMP_LINK__&&__Python__&&__JUMP_LINK , do not post a new question in this existing discussion. create your own thread in the q&a section. to get help, it is better for you to start your own post, otherwise poeple will not get aware of you. also keep in mind that we need: > a clear task description with input / output sample > a link that points to your code try > a description what exactly your issue is, (if possible including an error message)
14th Aug 2024, 6:40 PM
Lothar
Lothar - avatar
+ 1
Thnx
13th Aug 2024, 11:53 AM
[ Laur€nt ]
+ 1
Also, can you help me with this? In JavaScript, to have the result fixed to x digits after the decimal point, we use the toFixed(x) function, what is the equivalent in python ?
13th Aug 2024, 11:54 AM
[ Laur€nt ]
+ 1
Lothar cool thnx bro
13th Aug 2024, 12:54 PM
[ Laur€nt ]
+ 1
Now I have solved 25┌⁠(⁠・⁠。⁠・⁠)⁠┘⁠♪(⁠^⁠∇⁠^⁠)⁠ノ⁠♪
13th Aug 2024, 1:02 PM
[ Laur€nt ]
+ 1
Use ceil and floor functiona to get efficient result
15th Aug 2024, 6:12 AM
REDDY GURUNADA RAO
0
Wong Hei Ming thnx bro
13th Aug 2024, 1:00 PM
[ Laur€nt ]
0
***JUMP_LINK__&&__Python__&&__JUMP_LINK Go to "create" then to "discuss" and ask your question, someone will surely have an answer to your question.
14th Aug 2024, 6:52 PM
[ Laur€nt ]