Converting Float to Dollars and Cents

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

提交回复
热议问题