How to Format Currency in Python: Simple and Clear Guide
To format currency in Python, use
f-strings with formatting specifiers like {value:,.2f} for two decimals and commas. For locale-aware currency, use the locale module to format numbers according to regional settings.Syntax
You can format currency in Python using f-strings with format specifiers or the locale module for regional formatting.
f"${value:,.2f}": Formatsvaluewith commas and two decimals, adding a dollar sign.locale.currency(value): Formatsvalueaccording to the current locale's currency style.
python
value = 1234567.891 formatted = f"${value:,.2f}" import locale locale.setlocale(locale.LC_ALL, '') currency_locale = locale.currency(value)
Example
This example shows how to format a number as US dollars using f-strings and how to use the locale module to format currency based on your system's locale.
python
value = 1234567.891 # Using f-string for simple formatting formatted_simple = f"${value:,.2f}" print(formatted_simple) # Output: $1,234,567.89 # Using locale for currency formatting import locale locale.setlocale(locale.LC_ALL, '') # Use user's locale settings formatted_locale = locale.currency(value) print(formatted_locale) # Output depends on locale, e.g., $1,234,567.89
Output
$1,234,567.89
$1,234,567.89
Common Pitfalls
Common mistakes when formatting currency in Python include:
- Not setting the locale before using
locale.currency(), which can cause errors or unexpected output. - Using
str.format()orf-stringswithout commas, making large numbers hard to read. - Assuming
locale.currency()always uses the dollar sign; it depends on your system locale.
python
import locale value = 1234.5 # Wrong: Not setting locale before currency formatting try: print(locale.currency(value)) # May raise error or show default except Exception as e: print(f"Error: {e}") # Right: Set locale first locale.setlocale(locale.LC_ALL, '') print(locale.currency(value)) # Correct output based on locale # Wrong: No commas in f-string print(f"${value:.2f}") # Output: $1234.50 # Right: With commas print(f"${value:,.2f}") # Output: $1,234.50
Output
Error: unsupported locale setting
$1234.50
$1,234.50
Quick Reference
| Method | Usage | Output Example |
|---|---|---|
| f-string | f"${value:,.2f}" | $1,234,567.89 |
| locale.currency | locale.currency(value) | $1,234,567.89 (locale dependent) |
| format() | "${:,.2f}".format(value) | $1,234,567.89 |
Key Takeaways
Use f-strings with format specifiers like :,.2f to format currency with commas and two decimals.
Use the locale module to format currency according to regional settings after setting the locale.
Always set the locale before calling locale.currency() to avoid errors.
Remember that locale.currency output depends on your system's locale and may not always use the dollar sign.
Including commas improves readability for large currency values.