Formatting currency converts the currency amount of floating or integer type into a comma-separated string that represents the amount of money.
The majority of the currencies separate every three digits of its value by a comma and the fractional part of the currency by a period, the rest do the opposite.
Here are both ways of formatting the currency in Python.
Format currency using str.format()
If you call the built-in str.format(float)
method with str
as {:,.2f}
and float
as the currency value, it will format the currency in comma-separated form.
>>> amount = 82341.28
>>> currency = "{:,.2f}".format(amount)
>>> currency
'82,341.28'
If you need to also output the currency symbol such as $ for dollar, you use str
as ${:,.2f}
.
>>> currency = "${:,.2f}".format(amount)
>>> currency
'$82,341.28'
Format as period (.) separated currency
In case, the currency separates the main currency part by period (.) and fractional part by comma (,), split the main and fraction part of the currency by using the str.split(sep)
method with sep
as "."
, replace the “,” with “.” in the main currency part and concatenate them back together to form the new string.
>>> amount = 30045.91
>>> currency = "${:,.2f}".format(amount)
>>> main_currency, fractional_currency = currency.split('.')
>>> new_main_currency = main_currency.replace(',', '.')
>>> currency = new_main_currency + "," + fractional_currency
>>> currency
'$30.045,91'
Format currency using locale.currency()
Use the locale.currency(currency, grouping=True)
method of the locale module to convert the currency
value to a string representation of an amount of money in dollars.
>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
>>> currency = locale.currency(75166.12, grouping=True)
>>> currency
'$75,166.12'