How to Format a Float as Currency in Python
This code defines a function that converts a float to a string formatted as US currency with two decimal places and comma separators.
Python code
7 linesdef format_currency(amount):
return f"${amount:,.2f}"
if __name__ == "__main__":
test_amounts = [1234.5, 0, 9999999.999, -42.867]
for amount in test_amounts:
print(f"{amount} -> {format_currency(amount)}")
Output
1234.5 -> $1,234.50
0 -> $0.00
9999999.999 -> $10,000,000.00
-42.867 -> $-42.87
How it works
The function uses an f-string with format specifiers ,.2f. The comma adds thousands separators, and .2f rounds the number to two decimal places. The dollar sign is included directly in the string. Negative numbers produce a leading minus sign before the dollar symbol. This is a concise and readable way to format currency without external libraries, suitable for simple display purposes.
Common mistakes
- Forgetting the comma in the format specifier, resulting in missing thousands separators
- Using `round` on the float before formatting, which can cause floating-point rounding issues
- Not accounting for different currency symbols or locale-specific formatting
Variations
- Use the `locale` module to respect regional currency conventions
- Use the `decimal` module for exact arithmetic if high precision is required
Real-world use cases
- Displaying prices in an e-commerce order summary or product list.
- Formatting financial report values for a dashboard or PDF export.
- Showing transaction amounts in a bank statement or accounting application.
Sponsored
More from Strings & text
- Automatically Detect Weak Passwords from Large Password Lists in Python easy
- Build CSV row from Python list with proper quoting easy
- Build a Secure Password Strength Checker in Python easy
- Convert Natural Language Dates to Datetime in Python medium
- Count Characters, Words, and Lines in Python Text easy
- Extract Data from Strings in Python: Beginner's Guide easy
Keep learning
Related tutorials and quizzes for this topic.