Converting Float to Dollars and Cents

后端 未结 6 1086
北恋
北恋 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 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)

提交回复
热议问题