简体   繁体   English

货币格式的Python字符串

[英]Python string with currency formatted

I am attempting to retrieve a dollar amount from my database, concatenate it with other information and have it print with 2 decimal points. 我试图从数据库中检索美元金额,将其与其他信息连接起来,并用2个小数点打印。 I have tried so many different configurations I have lost tract but continue to get only one decimal point (or an error). 我已经尝试了很多不同的配置,但我却失去了很多,但仍然只能得到一个小数点(或一个错误)。 Can someone please show me where I am losing it. 有人可以告诉我我在哪里丢失它。

 #get payments on the permits
 for i in range(len(IDS)):  
     paydate = date.today() - timedelta(30)
     query = '''select `AmountPaid_credit`, `PayComment`, `DateReceived`, `WPTSinvoiceNo`
                 from Payments 
                 where `NPDES_ID` = ? and `DateReceived` >= ?'''
     PayStrings.append("\tNo Payment Recieved")
     for row in cur.execute(query, (IDS[i],paydate)):
         WPTSInv.append(row[3])
         d= row[2].strftime('%m/%d/%Y')
         #create a payment string 
         PayStrings[i]="\t$"+str(row[0])+" - "+d+" - "+row[1]

returns this 返回这个

$2000.0 - 02/09/2017 - 2017 APPLICATION FEE

but I need this 但是我需要这个

$2000.00 - 02/09/2017 - 2017 APPLICATION FEE

As an alternative to Haifeng's answer, you could do the following 作为海丰的替代选择,您可以执行以下操作

from decimal import Decimal

str(round(Decimal(row[0]), 2))

Edit: I would also like to add that there is a locale module and that it is probably a better solution, even if it is a little bit more work. 编辑:我还想补充一点,它有一个locale模块,这可能是一个更好的解决方案,即使还有更多工作要做。 You can see how to use it at this question here: Currency formatting in Python 您可以在以下问题中查看如何使用它: Python中的货币格式

In your case, you just converting decimal places: 就您而言,您只需转换小数位:

   >>> value = "2000.0"
   >>> "{:.2f}".format(float(value))
   '2000.00'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM