我正在尝试让Python将简单的Tip Calculator程序的输出四舍五入到两位小数,但到目前为止我还没有意识到这一点。以下是相关的代码部分。我希望输出以常规美元和美分格式打印(例如,$ XX.XX)
bill = float(input("\n\nWhat is the bill for your meal?: $"))
low_tip = bill * .15
print("\nIf you would like to tip the waiter 15%, the amount of the \ntip is: $", low_tip)
low_total = bill + low_tip
print("\nSo, your total bill including a 15% tip would be: $", low_total)
high_tip = bill * .20
print("\nIf you would like to tip the waiter 20%, the amount of the \ntip is: $", high_tip)
high_total = bill + high_tip
print("\nSo, your total bill including a 20% tip would be: $", high_total)
答案 0 :(得分:2)
您可以在打印前将浮动格式化为字符串:
>>> '${0:.2f}'.format(15.5)
'$15.50'
或使用%
运算符:
>>>'$%.2f' % 15.5
'$15.50'
整个print
看起来像是:
print("\nSo, your total bill including a 20% tip would be: ${0:.2f}".format(high_total))