Converting Float to Dollars and Cents

后端 未结 6 1072
北恋
北恋 2020-12-02 10:39

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

相关标签:
6条回答
  • 2020-12-02 10:49

    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 )
    
    0 讨论(0)
  • 2020-12-02 11:00

    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'
    
    0 讨论(0)
  • 2020-12-02 11:01

    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)
    
    0 讨论(0)
  • 2020-12-02 11:04

    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.

    0 讨论(0)
  • 2020-12-02 11:07
    df_buy['BUY'] = df_buy['BUY'].astype('float')
    df_buy['BUY'] = ['€ {:,.2f}'.format(i) for i in list(df_buy['BUY'])]
    
    0 讨论(0)
  • 2020-12-02 11:09

    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)

    0 讨论(0)
提交回复
热议问题