Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Float to Dollars and Cents

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
like image 852
Evorlor Avatar asked Jan 18 '14 18:01

Evorlor


People also ask

How do you format dollars into cents?

United States (U.S.) currency is formatted with a decimal point (.) as a separator between the dollars and cents. Some countries use a comma (,) instead of a decimal to indicate that separation.

How do you convert a number to a dollar in Python?

format(money). For example, try money = '${:,. 2f}'. format(money), and then print out money.

How do you convert a string to a float in Python?

We can convert a string to float in Python using the float() function. This is a built-in function used to convert an object to a floating point number. Internally, the float() function calls specified object __float__() function.


3 Answers

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.

like image 171
Justin O Barber Avatar answered Oct 22 '22 23:10

Justin O Barber


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'
like image 16
Lewis Avatar answered Oct 22 '22 23:10

Lewis


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)
like image 15
Alec Avatar answered Oct 22 '22 21:10

Alec