# Python 3, an Illustrated Tour Transcripts Chapter: Numbers Lecture: Rounding

0:00 In this video, we're going to talk about rounding. Let's read from what's new in Python 3
0:06 the round function, rounding strategy in return type have changed, exact halfway cases are now rounded to the nearest even result
0:14 instead of away from 0, for example round 2.5 now returns 2 rather than 3. So if you're not familiar with this, this is called banker's rounding
0:25 and we round towards the nearest even number so round 2.5, 2 is even 3 is not even, so it's going to round it to 2.
0:34 Round 3.5, 3 is not even 4 is, so it's going to round it to 4. And why is this called banker's rounding
0:41 is because if you're rounding and you're in a bank and you always round up you're going to bias towards the high end
0:47 and you're biased towards more than what you actually have. If you round towards even, then you're alternating
0:53 and presumably your bias is going to offset one another and in the end you'll come out more accurate. That's the theory behind rounding towards even.
1:03 And here's just a slide that says what I just said to the nearest even number is called banker's rounding it tries to eliminate bias to rounding high.
1:12 One thing to be aware of is this, note in the Python docs it says the behavior of round for floats can be surprising
1:19 for example, round 2.6752 gives to 2.67 instead of the expected 2.68 this is not a bug, it's a result of the fact that most decimal fractions
1:31 can't be represented exactly as a float. So what's going under the covers there is that 2.675 if you create a number that represents that
1:43 it's actually going to be closer to 2.67 than 2.68 and so when you round it to two places,
1:50 Python is going to note that and it's going to round it correctly, even though to us users, who at least in the US,
1:57 I think it's a US-centric view that you round up and this is rounding to what's more close, even though 2.675 seems closer to some people to 2.68.
2:09 Here's an example of that. I can say round 0.5 to 1 digit and round .15 to 1 digit of precision
2:17 those both round to .1 and that's because under the covers the float number that represents them is actually closer to those numbers
2:26 than the other option for rounding. So this is something that's new in Python 3.
2:32 I personally ran into this when I was doing some work on porting some Excel spreadsheets and so interesting behavior here,
2:40 but again, the bias is towards being more correct in the average term rather than always rounding up.

Talk Python's Mastodon Michael Kennedy's Mastodon