How does round() work. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How does round() work.

Can someone explain how roind works in python: Sample input : print(round(3.5)) print(round(4.5)) Sample output: 4 4 Acording to the way I understand it .The result should be 4 and 5. Please explain

1st Oct 2021, 1:09 AM
Richard
Richard - avatar
3 Answers
+ 6
Hi Richard! That's because Python3 uses Bankers Rounding or round half to even which rounds .5 values to the closest even number. So, output is always an even number for rounding values of .5 .That's why round(3.5) gives 4 whereas the same 4 is for round(4.5). You can refer this article to understand its concept clearly. https://en.m.wikipedia.org/wiki/Rounding#Round_half_to_even
1st Oct 2021, 1:39 AM
Python Learner
Python Learner - avatar
+ 4
Here is a very good explanation of why this is happening: https://stackoverflow.com/questions/10825926/JUMP_LINK__&&__python__&&__JUMP_LINK-3-x-rounding-behavior But if you want to specifically round up or down you could use math.ceil() and math.floor() relatively. (see code below) https://code.sololearn.com/cNmEHrOrgV9i/?ref=app
1st Oct 2021, 1:45 AM
Aleksei Radchenkov
Aleksei Radchenkov - avatar
+ 2
Good to know. I was surprised that python does this and even more surprised that there is actually a good reason for it.
1st Oct 2021, 2:37 AM
Simon Sauter
Simon Sauter - avatar