[英]Python string with currency formatted
我试图从数据库中检索美元金额,将其与其他信息连接起来,并用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
作为海丰的替代选择,您可以执行以下操作
from decimal import Decimal
str(round(Decimal(row[0]), 2))
编辑:我还想补充一点,它有一个locale
模块,这可能是一个更好的解决方案,即使还有更多工作要做。 您可以在以下问题中查看如何使用它: Python中的货币格式
就您而言,您只需转换小数位:
>>> value = "2000.0"
>>> "{:.2f}".format(float(value))
'2000.00'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.