我正在为学校做一个项目,最后我要总结客户(用户)账单。
如果我删除了“%.2f”,那么我不会收到错误消息,但显示的数字会不断出现。如何只显示最后 2 位小数?
我正在使用的代码:
print('Amount Due: $' + '%.2f' % baseCharge)
我收到的输出:
print('Amount Due: $' + '%.2f' % baseCharge)
TypeError: a float is required
完整代码:
rentalCode = input("(B)udget, (D)aily, or (W)eekly rental?\n")
weeksRented = 0
daysRented = 0
budgetCharge = 40
dailyCharge = 60
weeklyCharge = 190
if rentalCode == 'B' or rentalCode == 'D':
daysRented = input("Number of Days Rented:") #Prompt --> "Number of Days Rented:"
else:
weeksRented = input("Number of Weeks Rented:\n") #Prompt --> "Number of Weeks Rented:"
odoStart = int(input("Starting Odometer Reading:\n"))
odoEnd = int(input("Ending Odometer Reading:\n"))
totalMiles = odoEnd - odoStart
print(rentalCode) # Displays Chosen Rental Code
if rentalCode == 'B' or rentalCode == 'D': # Decides which option has been input and displays the output
print(daysRented)
else:
print(weeksRented)
baseCharge = 0
if rentalCode == 'B':
baseCharge = daysRented * budgetCharge
elif rentalCode == 'D':
baseCharge = daysRented * dailyCharge
elif rentalCode == 'W':
baseCharge = weeksRented * weeklyCharge
#Print odoStart, odoEnd and totalMiles
print(odoStart)
print(odoEnd)
print(totalMiles)
# Calculate Charges 2
totalCharge = 0
if rentalCode == 'B':
totalCharge = baseCharge + str(totalMiles * .25)
elif rentalCode == 'D':
averageDayMiles = int(totalMiles) / int(daysRented)
if averageDayMiles <= 100:
totalCharge = baseCharge
else:
extraMiles = totalMiles - 100
totalCharge = baseCharge + str(extraMiles * .25)
elif rentalCode == 'W':
averageWeekMiles = int(totalMiles) / int(weeksRented)
if averageWeekMiles <= 900:
totalCharge = baseCharge
else:
totalCharge = baseCharge + str(weeksRented * 100)
print(totalCharge)
if rentalCode == "W":
rentalPeriod = weeksRented
else:
rentalPeriod = daysRented
print(rentalPeriod)
if rentalCode == "B":
baseCharge = budgetCharge * rentalPeriod
elif rentalCode == "D":
baseCharge = dailyCharge * rentalPeriod
else:
baseCharge = weeklyCharge * rentalPeriod
print('Customer Summary')
print('Rental Code: ' + rentalCode)
print('Rental Period: ' + rentalPeriod)
print('Starting Odometer: ' + str(odoStart))
print('Ending Odometer: ' + str(odoEnd))
print('Miles Driven: ' + str(totalMiles))
print('Amount Due: $' + '%.2f' % baseCharge)
同样,如果 %.2f 存在,我会收到输出错误,但如果我把它拿出来,我会收到一个很大的数字。示例:而不是 951.65 我会得到 951.6555555555555555555 等