Python字符串与货币格式化

时间:2017-02-15 21:05:12

标签: python-3.x

我正在尝试从我的数据库中检索一个美元金额,将其与其他信息连接起来并打印出2个小数点。我已经尝试了很多不同的配置,我已经丢失了但仍然只得到一个小数点(或错误)。有人可以告诉我我失去它的地方。

 #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]

返回此

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

但我需要这个

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

2 个答案:

答案 0 :(得分:2)

作为海峰答案的替代方案,您可以执行以下操作

from decimal import Decimal

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

编辑:我还想补充说,有一个locale模块,它可能是一个更好的解决方案,即使它是一个更多的工作。您可以在此处查看如何使用此问题:Currency formatting in Python

答案 1 :(得分:1)

在您的情况下,您只需转换小数位:

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