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.

Easy Python 3.9+ Aug 9, 2026 Strings & text 13 views 0 copies

Python code

7 lines
Python 3.9+
def 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

stdout
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

  1. Use the `locale` module to respect regional currency conventions
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Strings & text

Related tutorials and quizzes for this topic.