A brief note on rounding numbers in Python 3.
Python provides a built-in function for rounding numbers: round
.
round(number[, ndigits])
This function rounds the number to ndigits
decimal places (by default, zero decimal places, i.e., to the nearest integer).
Examples:
round(1.5)
round(2.5)
round(2.65, 1)
round(2.75, 1)
There is a peculiarity that is important to be aware of and is often overlooked.
From school, many are used to the fact that when the (N + 1)th digit is 5 and subsequent digits are zero, rounding always goes towards the larger magnitude.
However, as can be seen from the examples, this is not the case in Python. Here, the so-called “bank rounding” is used, which means rounding to the nearest even number.
In practice, this is not as critical. For example:
round(2.85, 1)
Something seems off, right? Actually, everything is as intended. It’s just that due to precision issues with floating-point numbers, this number is slightly more than 2.85, and hence it gets rounded to 2.9.
You can see this with the fractions
module:
from fractions import Fraction
a = Fraction(2.85)
b = Fraction('2.85')
print(a == b)
print(a > b)