How to Format Decimal Output in Python
In Python, controlling how numbers are displayed is essential for creating readable reports, user interfaces, or data logs. Whether you are dealing with currency, scientific measurements, or percentages, simply printing a raw float often results in unwanted precision (e.g., 10.12999999).
This guide covers the most efficient methods to format decimal numbers using f-strings, the format() method, and the decimal module for high-precision arithmetic.
Method 1: Using f-Strings (Recommended)
Introduced in Python 3.6, f-strings (Formatted String Literals) are the standard way to format output. They are concise, readable, and faster than older methods.
The syntax {variable:.Nf} formats a number as a fixed-point number with N decimal places.
val = 12.34567
# ✅ Standard rounding to 2 decimal places
print(f"Two decimals: {val:.2f}")
# ✅ Rounding to 0 decimal places
print(f"No decimals: {val:.0f}")
# ✅ Force sign display (+/-)
print(f"With sign: {val:+.2f}")
Output:
Two decimals: 12.35
No decimals: 12
With sign: +12.35
Python's string formatting automatically rounds the last digit. 12.34567 becomes 12.35 when using .2f.
Method 2: Using the format() Method
For Python versions older than 3.6, or when building format strings dynamically, the .format() method is used. The specifiers (like .2f) remain the same.
val = 99.9
# ✅ Using .format()
print("Percentage: {:.2f}%".format(val))
# ✅ Reusing variables
print("Value: {0:.2f} (Again: {0:.1f})".format(val))
Output:
Percentage: 99.90%
Value: 99.90 (Again: 99.9)
Formatting for Currency (Thousands Separators)
When displaying financial data, adding commas as thousands separators improves readability. You can combine the comma separator with the decimal precision specifier.
revenue = 1234567.8912
# ✅ Format with comma separator and 2 decimal places
print(f"Revenue: ${revenue:,.2f}")
# ✅ Format with underscore separator (Python 3.6+)
print(f"Machine readable: {revenue:_.2f}")
Output:
Revenue: $1,234,567.89
Machine readable: 1_234_567.89
Handling High Precision with the Decimal Module
Standard floating-point numbers in Python uses binary approximation, which can lead to precision errors in financial calculations. The decimal.Decimal class offers exact arithmetic.
The Floating Point Issue
# ⛔️ Floating point arithmetic error
price = 1.1 + 2.2
print(f"Float math: {price}")
# Formatting hides the error visually, but the value remains imprecise
print(f"Formatted float: {price:.2f}")
Output:
Float math: 3.3000000000000003
Formatted float: 3.30
The Decimal Solution
from decimal import Decimal
# ✅ Exact arithmetic
# Note: Always pass numbers as strings to Decimal()
exact_price = Decimal('1.1') + Decimal('2.2')
print(f"Decimal math: {exact_price}")
print(f"Formatted Decimal: {exact_price:.2f}")
Output:
Decimal math: 3.3
Formatted Decimal: 3.30
Always initialize Decimal objects with strings (e.g., Decimal('1.1')). Initializing with a float (e.g., Decimal(1.1)) inherits the float's existing imprecision.
Scientific Notation and Alignment
For scientific data or generating tables, you may need exponential notation or specific text alignment.
Scientific Notation
Use the e or E type code.
atom_weight = 0.0000000000234
# ✅ Scientific notation with 2 significant decimals
print(f"Weight: {atom_weight:.2e}")
Output:
Weight: 2.34e-11
Alignment (Padding)
You can set a fixed width for numbers to align columns in text output.
>: Right align (default for numbers)<: Left align^: Center align
numbers = [1, 10, 100, 1000]
print("Right Aligned:")
for n in numbers:
# Width of 6, 2 decimal places
print(f"|{n:8.2f}|")
Output:
Right Aligned:
| 1.00|
| 10.00|
| 100.00|
| 1000.00|
Conclusion
To format decimal output in Python effectively:
- Use f-strings (
f"{value:.2f}") for standard formatting needs. - Use
,.2fto add thousands separators for currency. - Use
decimal.Decimalfor financial calculations to avoid floating-point errors. - Use padding (e.g.,
:10.2f) when generating text-based tables.