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
print(f"Two decimals: {val:.2f}")
print(f"No decimals: {val:.0f}")
print(f"With sign: {val:+.2f}")Output:
Two decimals: 12.35
No decimals: 12
With sign: +12.35Method 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
print("Percentage: {:.2f}%".format(val))
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
print(f"Revenue: ${revenue:,.2f}")
print(f"Machine readable: {revenue:_.2f}")Output:
Revenue: $1,234,567.89
Machine readable: 1_234_567.89Handling 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
price = 1.1 + 2.2
print(f"Float math: {price}")
print(f"Formatted float: {price:.2f}")Output:
Float math: 3.3000000000000003
Formatted float: 3.30The Decimal Solution
from decimal import 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.30Scientific 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
print(f"Weight: {atom_weight:.2e}")Output:
Weight: 2.34e-11Alignment (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:
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.