To format numbers as currency in Python, the easiest way is with the locale module.
import locale
locale.setlocale( locale.LC_ALL, '' )
amt = 1234.56
print(locale.currency(amt))
print(locale.currency(amt, grouping=True))
#Output:
$1234.56
$1,234.56
You can also use the string format() function.
amt = 1234.56
print("${:.2f}".format(amt))
print("${:0,.2f}".format(amt))
#Output:
$1234.56
$1,234.56
Finally, you can use the babel.numbers module to format numbers as money and currency.
import babel.numbers
amt = 1234.56
print(babel.numbers.format_currency(amt, "USD", locale='en_US'))
#Output:
$1,234.56
When working with numbers in Python, many times you need to format those numbers a certain way.
One such situation is if you have an application or program which is working with numbers representing money.
To format numbers as a specific currency, you can use the Python locale module.
For example, you can create a dollar format in Python in the following way with the locale module.
import locale
locale.setlocale( locale.LC_ALL, '' )
amt = 1234.56
print(locale.currency(amt))
#Output:
$1234.56
If you want to add commas to the currency format with the locale module, pass ‘grouping=True’ to currency().
import locale
locale.setlocale( locale.LC_ALL, '' )
amt = 1234.56
print(locale.currency(amt, grouping=True))
#Output:
$1,234.56
If you want to change the locale, then you can use the setlocale() function.
Using String format() to Create a Currency Format in Python
If you know how to deal with the cultural differences of how numbers are treated and formatted, you can use the Python string format function to create a currency format.
For example, to format a number with a dollar format in Python, the easiest way is using the Python string formatting function format().
Below shows some examples using the string format() function to create money formats in Python.
amt = 1234.56
print("${:.2f}".format(amt))
print("${:0,.2f}".format(amt))
#Output:
$1234.56
$1,234.56
Using babel Module to Format Numbers as Currency in python
One last way to format numbers as money is with the babel.numbers module.
The format_currency() function gives you a number of options to format numbers as different currencies.
Below is a simple example showing you how to use format_currency() from the babel.numbers module in Python to create a currency format.
import babel.numbers
amt = 1234.56
print(babel.numbers.format_currency(amt, "USD", locale='en_US'))
#Output:
$1,234.56
Hopefully this article has been useful for you to learn how to format numbers as currency in Python.