Format numbers as currency strings using the locale Module

The locale module provides a way to the format numbers as currency strings according to user’s locale settings. It uses the locale.currency() function for the formatting.

import locale
# Set the locale to the user's default
locale.setlocale(locale.LC_ALL, '')
# Format a number as a currency string
currency_string = locale.currency(1234.56, grouping=True)
  • locale.currency(value, symbol=True, grouping=False) – The Formats value as a currency string according to locale settings.
  • value – The numeric value to the format.
  • symbol – If True, include the currency symbol in the output.
  • grouping – If True, use the grouping settings specified in locale.

Below is the implementation for formatting numbers as currency strings using the locale module in Python:

Python
import locale
# Set the locale to default 'C' locale
locale.setlocale(locale.LC_ALL, 'C')
# Define a function to the format the currency string
def format_currency(amount):
    return '${:,.2f}'.format(amount)
# Format a number as a currency string using defined function
GFG = format_currency(1234.56)
print(GFG)

Output
$1,234.56

In this code:

  • We set the locale to default ‘C’ locale in which should always be available.
  • We define a function format_currency that takes a numeric value as the input and formats it as the currency string using the string formatting with ‘{:,.2f}’ format specifier.
  • We then call the format_currency() function with desired numeric value to the obtain the currency string.

How to format numbers as currency strings in Python

Formatting numbers as currency strings in Python is a common requirement especially in the applications involving financial data. Formatting numbers as currency strings in Python involves presenting numeric values in the standardized currency format typically including the currency symbol, thousands separators and the number of the decimal places. Python provides the several ways to the format numbers as currency strings including the locale module and str.format() method.

Similar Reads

Format numbers as currency strings using the locale Module:

The locale module provides a way to the format numbers as currency strings according to user’s locale settings. It uses the locale.currency() function for the formatting....

Format numbers as currency strings using str.format():

Another way to format numbers as currency strings is to the use the str.format() method with the format specifier for currency....