Python round() Method
The round()
method returns a floating-point number, rounded to the specified number of the decimal point.
Syntax:
round(number, digits)
Parameters:
- number: The number to be rounded off.
- digits: (Optional) The number of digits to round off. Defaults to 0.
Return Value:
Returns an integer if digits parameter is not given, otherwise returns a floating point number rounded off to the specified digits.
The following example demonstrates the round()
method.
print(round(1))
print(round(1.4))
print(round(1.5))
print(round(1.6))
1
1
2
2
In the above example, round(1.4)
returns nearest int value which is 1, but round(1.5)
returns 2.
If the number of digits are specifies as a parameter, it will round off to that many digits.
print(round(10.544,2))
print(round(10.545,2))
print(round(10.546,2))
print(round(10.546,3))
10.54
10.54
10.55
10.546
Now, consider the following example.
print(round(3.665,2))
print(round(3.675,2))
3.67
3.67
Above, 3.665 rounded off to 3.67 and 3.675 is also rounded off to 3.67 instead of 2.68. This is because most decimal fractions can't be represented exactly as a float. Visit Floating Point Arithmetic: Issues and Limitations for more information.