I am attempting to retrieve a dollar amount from my database, concatenate it with other information and have it print with 2 decimal points. 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. You can see how to use it at this question here: Currency formatting in Python
In your case, you just converting decimal places:
>>> value = "2000.0"
>>> "{:.2f}".format(float(value))
'2000.00'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.