+ 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
3 ответов
+ 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
+ 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
+ 2
Good to know. I was surprised that python does this and even more surprised that there is actually a good reason for it.