Converting Float to Dollars and Cents
In Python 3.x and 2.7, you can simply do this:
>>> '${:,.2f}'.format(1234.5)'$1,234.50'
The :,
adds a comma as a thousands separator, and the .2f
limits the string to two decimal places (or adds enough zeroes to get to 2 decimal places, as the case may be) at the end.
Building on @JustinBarber's example and noting @eric.frederich's comment, if you want to format negative values like -$1,000.00
rather than $-1,000.00
and don't want to use locale
:
def as_currency(amount): if amount >= 0: return '${:,.2f}'.format(amount) else: return '-${:,.2f}'.format(-amount)
In python 3, you can use:
import localelocale.setlocale( locale.LC_ALL, 'English_United States.1252' )locale.currency( 1234.50, grouping = True )
Output
'$1,234.50'