Python round() function is used to perform rounding operation on numbers.
Table of Contents
Python round() function syntax is:
The number is rounded to ndigits precision after the decimal point.
If ndigit is not provided or is None, then nearest integer is returned.
While rounding the input number to an integer, if both round up and round down values are equally close then even number is returned. For example, 10.5 will be rounded to 10 whereas 11.5 will be rounded to 12.
Any integer value is valid for ndigits (positive, zero, or negative).
Python round() function examples
Let’s look at some example of round() function.
round() to integer
Copyprint(round(10, 2)) print(round(10.2)) print(round(10.8)) print(round(11.5))
Copy10 10 11 12
round() to even side
Copy# if both side of rounding is same, even is returned print(round(10.5)) print(round(12.5))
round() with ndigit as None
Copyprint(round(1.5)) # OR print(round(1.5, None))
round() with negative ndigit
Copyprint(round(100, 0)) print(round(100.1234, -4)) print(round(100.1234, -5))
Copy100 100.0 0.0
Python round float
When rounding is applied on floating point numbers, the result can be sometimes surprising. It’s because the numbers are stored in binary format and mostly decimal fractions cannot be represented exactly as binary fractions.
Python does the approximation and presents us the rounded value, because of this floating point arithmetic can sometimes result in surprising values.
Copy>>>.1 + .1 == .2 True >>>.1 + .1 + .1 == .3 False >>>.1 + .1 + .1 + .1 == .4 True
Let’s see some examples of round() function with floats.
Copyprint(round(2.675, 2)) print(round(1.2356, 2)) print(round(-1.2356, 2))
Copy2.67 1.24 -1.24
Notice that first float rounding seems wrong. Ideally, it should be rounded to 2.68.
This is the limitation of arithmetic operations with floats, we shouldn’t rely on conditional logic when dealing with floating point numbers.
round() with custom object
We can use round() function with a custom object too if they implement __round__() function. Let’s look at an example.
Copyclass Data: id = 0 def __init__(self, i): self.id = i def __round__(self, n): return round(self.id, n) d = Data(10.5234) print(round(d, 2)) print(round(d, 1))
Reference: Official Documentation