Converting Float to Dollars and Cents

Evorlor picture Evorlor · Jan 18, 2014 · Viewed 107.7k times · Source

First of all, I have tried this post (among others): Currency formatting in Python. It has no affect on my variable. My best guess is that it is because I am using Python 3 and that was code for Python 2. (Unless I overlooked something, because I am new to Python).

I want to convert a float, such as 1234.5, to a String, such as "$1,234.50". How would I go about doing this?

And just in case, here is my code which compiled, but did not affect my variable:

money = float(1234.5)
locale.setlocale(locale.LC_ALL, '')
locale.currency(money, grouping=True)

Also unsuccessful:

money = float(1234.5)
print(money) #output is 1234.5
'${:,.2f}'.format(money)
print(money) #output is 1234.5

Answer

πόδας ὠκύς picture πόδας ὠκύς · Jan 18, 2014

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.