[python] 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

The answer is


df_buy['BUY'] = df_buy['BUY'].astype('float')
df_buy['BUY'] = ['€ {:,.2f}'.format(i) for i in list(df_buy['BUY'])]

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'

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)

you said that:

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

did not work.... Have you coded exactly that way? This should work (see the little difference):

money = float(1234.5)      #next you used format without printing, nor affecting value of "money"
amountAsFormattedString = '${:,.2f}'.format(money)
print( amountAsFormattedString )

Personally, I like this much better (which, granted, is just a different way of writing the currently selected "best answer"):

money = float(1234.5)
print('$' + format(money, ',.2f'))

Or, if you REALLY don't like "adding" multiple strings to combine them, you could do this instead:

money = float(1234.5)
print('${0}'.format(format(money, ',.2f')))

I just think both of these styles are a bit easier to read. :-)

(of course, you can still incorporate an If-Else to handle negative values as Eric suggests too)


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to python-3.x

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation Replace specific text with a redacted version using Python Upgrade to python 3.8 using conda "Permission Denied" trying to run Python on Windows 10 Python: 'ModuleNotFoundError' when trying to import module from imported package What is the meaning of "Failed building wheel for X" in pip install? How to downgrade python from 3.7 to 3.6 I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."? Iterating over arrays in Python 3 How to upgrade Python version to 3.7?

Examples related to floating-point

Convert list or numpy array of single element to float in python Convert float to string with precision & number of decimal digits specified? Float and double datatype in Java C convert floating point to int Convert String to Float in Swift How do I change data-type of pandas data frame to string with a defined format? How to check if a float value is a whole number Convert floats to ints in Pandas? Converting Float to Dollars and Cents Format / Suppress Scientific Notation from Python Pandas Aggregation Results

Examples related to string-formatting

JavaScript Chart.js - Custom data formatting to display on tooltip Format in kotlin string templates Converting Float to Dollars and Cents Chart.js - Formatting Y axis String.Format not work in TypeScript Use StringFormat to add a string to a WPF XAML binding How to format number of decimal places in wpf using style/template? How to left align a fixed width string? Convert Java Date to UTC String Format a Go string without printing?

Examples related to currency

Converting Float to Dollars and Cents Best data type to store money values in MySQL How to use GOOGLEFINANCE(("CURRENCY:EURAUD")) function What data type to use for money in Java? Cast a Double Variable to Decimal Yahoo Finance All Currencies quote API Documentation How can I correctly format currency using jquery? Currency format for display Print Currency Number Format in PHP Why not use Double or Float to represent currency?