Python locale.currency() Function
The Python locale.currency() function is used to format a given number as a currency string according to the locale settings. It allows displaying currency values with appropriate symbols, separators, and decimal formatting.
This function is useful for representing monetary values in a localized format without manually handling currency symbols or decimal separators.
Syntax
Following is the syntax of the Python locale.currency() function −
locale.currency(val, symbol=True, grouping=False, international=False)
Parameters
This function accepts the following parameters −
- val: The numeric value to be formatted as currency.
- symbol (Optional): A boolean value indicating whether to include the currency symbol. Default is True.
- grouping (Optional): A boolean value indicating whether to use a thousands separator. Default is False.
- international (Optional): A boolean value indicating whether to use the international currency symbol. Default is False.
Return Value
This function returns a formatted currency string based on the locale settings.
Example 1
Following is an example of the Python locale.currency() function. Here, we format a number as currency −
import locale
locale.setlocale(locale.LC_ALL, '')
currency_value = locale.currency(1234.56)
print("Formatted Currency:", currency_value)
Following is the output of the above code (output may vary depending on the system locale) −
Formatted Currency: ₹ 1234.56
Example 2
Here, we format the currency without the symbol using the locale.currency() function −
import locale
locale.setlocale(locale.LC_ALL, '')
currency_value = locale.currency(789.99, symbol=False)
print("Formatted Currency without Symbol:", currency_value)
Output of the above code is as follows (output may vary based on system settings) −
Formatted Currency without Symbol: 789.99
Example 3
Now, we use the locale.currency() function with thousands grouping enabled −
import locale
locale.setlocale(locale.LC_ALL, '')
currency_value = locale.currency(1234567.89, grouping=True)
print("Formatted Currency with Grouping:", currency_value)
The result obtained is as shown below (output may vary) −
Formatted Currency with Grouping: ₹ 12,34,567.89
Example 4
We can use the locale.currency() function with the international currency symbol −
import locale
locale.setlocale(locale.LC_ALL, '')
currency_value = locale.currency(99.99, international=True)
print("Formatted Currency with International Symbol:", currency_value)
The result produced is as follows (output may vary) −
Formatted Currency with International Symbol: INR 99.99
python_modules.htm