In Python, the round() function is used to round a floating-point number to a specified number of decimal places.
Function Syntax
round(number, ndigits=None)
Parameters:
number: The number to be rounded.ndigits: Optional parameter, the number of decimal places to retain. Default isNone.
The round() function uses bankers' rounding, also known as round half to even. For the last digit to be retained:
- Round Down (舍): If the part to be discarded is
< 0.5, simply discard it. - Round Up (入): If the part to be discarded is
> 0.5, round up. - Round Half to Even (五成双): If the part to be discarded is exactly
= 0.5, round to the nearest even number.
Examples of the round() Function
Common usage:
print(round(3.14)) # 3
print(round(-3.14)) # -3
# Specifying decimal places
print(round(3.14, 1)) # 3.1
print(round(3.14, 2)) # 3.14
# Negative ndigits
print(round(1234.56, -1)) # 1230.0
print(round(1234.56, -2)) # 1200.0
print(round(1234.56, -3)) # 1000.0
When the discarded part is exactly 5, round to the nearest even number:
print(round(0.5)) # 0
print(round(1.5)) # 2
print(round(2.5)) # 2
print(round(3.5)) # 4
print(round(4.5)) # 4
print(round(1.25, 1)) # 1.2
print(round(1.35, 1)) # 1.4
print(round(1.45, 1)) # 1.4
print(round(1.55, 1)) # 1.6
Floating-Point Precision Issues
In the following example, there is a floating-point precision issue:
print(round(2.675, 2)) # 2.67
print(round(2.685, 2)) # 2.69
This is because 2.675 cannot be represented exactly in binary. Its actual value might be:
x = 2.675
y = 2.685
print(f"{x} Actual value: {x:.20f}")
print(f"{y} Actual value: {y:.20f}")
2.675 Actual value: 2.67499999999999982236 2.685 Actual value: 2.68500000000000005329
Using the Decimal Type
Using the Decimal type can represent floating-point numbers more precisely:
from decimal import Decimal
x = Decimal('2.675')
y = Decimal('2.685')
print(round(x, 2)) # 2.68
print(round(y, 2)) # 2.68
Traditional Rounding (四舍五入)
Traditional rounding rules are as follows:
- Round Down (四舍): If the part to be discarded is
< 0.5, simply discard it. - Round Up (五入): If the part to be discarded is
>= 0.5, round up.
The following example is a Python implementation of traditional rounding:
from decimal import Decimal, ROUND_HALF_UP, getcontext
import math
def traditional_round_decimal(number, ndigits=0):
# Convert to Decimal
if isinstance(number, Decimal):
dec_number = number
else:
dec_number = Decimal(str(number))
# Set rounding mode
exponent = Decimal(f'1e-{ndigits}')
result = dec_number.quantize(exponent, rounding=ROUND_HALF_UP)
return result
print(traditional_round_decimal(3.14159,3)) # 3.142