Limit decimal places in Python
Use formatting for fixed-width display, round for a rounded numeric result, and Decimal when the required policy is defined in decimal arithmetic.
Decide whether you need a numeric result or a display string. round(x, 2) rounds a number; f"{x:.2f}" formats a string with exactly two digits after the decimal point.
Round a float
x = 3.14159265
rounded = round(x, 2)
print(rounded) # 3.14
The result is still a float when x is a float and a number of digits is specified. A float does not retain a decimal-place presentation rule: 3.0 and 3.00 are the same value.
Format for display
x = 3.14159265
print(f"{x:.2f}")
print("{:.2f}".format(x))
print("%.2f" % x)
print(f"{3.0:.2f}") # 3.00
These produce strings. Fixed-point f formatting avoids scientific notation for ordinary finite values; e formatting explicitly uses it. Formatting is not a way to change the stored precision of the original float.
Understand ties and binary approximation
print(round(2.5)) # 2
print(round(3.5)) # 4
print(round(0.575, 2)) # 0.57
Built-in rounding selects the even choice for exact halfway cases. However, many decimal fractions are not exactly representable as binary floats. The stored value of 0.575 is slightly below the exact decimal number, which explains that last result. Decimal formatting of a float is also affected by the value actually stored.
Choose an explicit decimal policy
from decimal import Decimal, ROUND_HALF_UP, ROUND_DOWN
value = Decimal("0.575")
print(value.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)) # 0.58
print(Decimal("-1.239").quantize(
Decimal("0.01"), rounding=ROUND_DOWN
)) # -1.23
Constructing from a decimal string preserves the intended decimal input. Constructing from an existing float preserves that float's approximation instead. ROUND_HALF_UP rounds ties away from zero; ROUND_DOWN truncates toward zero, including for negative numbers. Select the policy your application requires and account for the decimal context's precision during calculations.
FAQ
Can I truncate with int(x * 100) / 100? It truncates the scaled binary float toward zero, but binary approximation can cause an unexpected result near a decimal boundary. Use Decimal with an explicit rounding mode when exact decimal truncation is required.
Why does round not print trailing zeros? Numeric rounding and formatting serve different purposes. Use fixed-point formatting for presentation.
Does Decimal make every calculation exact? No. Inputs, division, context precision, and rounding still matter. It gives you decimal representation and explicit policies rather than unlimited precision for every operation.
References
Contact us
Join the community
to join the community
Try Guance
Start online and pay only for what you use.
Get startedChoose a Guance plan