How to Format Floating Point Numbers to Python Strings
Formatting floating-point numbers is a daily task in Python, whether you are rounding currency for a receipt, displaying scientific data, or calculating percentages for a report. Raw floats can often look messy (e.g., 1234.567800001), so mastering Python's formatting tools is essential for clean data presentation.
This guide explores the three primary methods for formatting floats: f-strings (the modern standard), str.format(), and the legacy % operator, along with practical examples for currency and scientific notation.
Method 1: Using F-Strings (Recommended)
Introduced in Python 3.6, f-strings (Formatted String Literals) are the fastest and most readable way to format numbers. You embed expressions directly inside string literals using {}.
Syntax:
f"{value:width.precisionf}"
:Starts the format specifier..2f: Fixed-point notation with 2 decimal places..1%: Percentage format.e: Scientific notation.
Example:
value = 3.14159
# ✅ Correct: Standard rounding to 2 decimals
print(f"Pi (2 decimals): {value:.2f}")
# ✅ Correct: Percentage format (multiplies by 100 automatically)
accuracy = 0.9855
print(f"Accuracy: {accuracy:.1%}")
# ✅ Correct: Scientific notation
large_num = 1234567.89
print(f"Scientific: {large_num:.2e}")
Output:
Pi (2 decimals): 3.14
Accuracy: 98.6%
Scientific: 1.23e+06
Rounding vs. Truncation: Formatting with .2f automatically rounds the number. For example, 3.149 becomes 3.15.
Method 2: Using the format() Method
Before f-strings, the .format() method was the standard. It remains useful for logging or when format strings are user-generated or stored in variables.
value = 123.45678
# Basic formatting
print("Value: {:.2f}".format(value))
# Reusing variables with indices
print("Coordinates: ({:.1f}, {:.1f})".format(10.55, 20.33))
Output:
Value: 123.46
Coordinates: (10.6, 20.3)
Method 3: Legacy % Formatting
This style is inherited from the C language (printf). While still supported, it is generally discouraged for new code due to being less readable than f-strings.
price = 19.99
# The old way
print("Price: %.2f" % price)
Output:
Price: 19.99
Practical Examples: Currency and Science
Formatting Currency with Commas
When dealing with money, you often need comma separators for thousands and strictly two decimal places.
balance = 1234567.89123
# comma (,) adds thousand separator
# .2f fixes decimals to 2
print(f"Account Balance: ${balance:,.2f}")
Output:
Account Balance: $1,234,567.89
Formatting Scientific Data
Scientific data often spans huge ranges. Using scientific notation ensures the output remains concise.
def format_measurements(measurements):
# Format list to 3 significant digits in scientific notation
return [f"{m:.3e}" for m in measurements]
readings = [0.000456, 12345.678]
print(f"Readings: {format_measurements(readings)}")
Output:
Readings: ['4.560e-04', '1.235e+04']
Conclusion
To format floating-point numbers in Python:
- Use F-Strings (
f"{val:.2f}") for almost all modern Python development. It is concise and fast. - Use
.format()if you are working with older Python versions (< 3.6) or deferred template strings. - Remember Precision: Floating-point math isn't perfect; formatting helps hide precision errors (e.g.,
0.1 + 0.2displayed as0.30instead of0.30000000000000004).