python – Converting Float to Dollars and Cents
python – 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 @JustinBarbers example and noting @eric.frederichs comment, if you want to format negative values like -$1,000.00
rather than $-1,000.00
and dont want to use locale
:
def as_currency(amount):
if amount >= 0:
return ${:,.2f}.format(amount)
else:
return -${:,.2f}.format(-amount)
python – Converting Float to Dollars and Cents
In python 3, you can use:
import locale
locale.setlocale( locale.LC_ALL, English_United States.1252 )
locale.currency( 1234.50, grouping = True )
Output
$1,234.50