0

我试图让 Python 将一个简单的提示计算器程序的输出四舍五入到小数点后两位,但到目前为止我还没有很高兴弄清楚它。下面是相关的代码部分。我希望以传统的美元和美分格式打印输出(例如,$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)
4

1 回答 1

2

您可以在打印之前将浮点数格式化为字符串:

>>> '${0:.2f}'.format(15.5)
'$15.50'

或使用%运算符:

>>>'$%.2f' % 15.5
'$15.50'

整个prints 看起来像:

print("\nSo, your total bill including a 20% tip would be: ${0:.2f}".format(high_total))
于 2013-04-17T15:30:44.530 回答