0

我是新手(比如 2 周),正在尝试学习 Python 2.7x。我正在尝试做一个基本程序,让用户输入一顿饭的费用,并输出 0.15 小费的费用。我希望输出看起来像 23.44(显示 2 位小数)

我的代码:

MealPrice = float(raw_input("Please type in your bill amount: "))
tip = float(MealPrice * 0.15,)
totalPrice = MealPrice+tip
int(totalPrice)

print "Your tip would be:               ",tip
print "Yout total bill would be:       ",totalPrice

我的输出:请输入您的账单金额:22.22 您的小费将是:3.333 您的总账单将是:25.553

4

1 回答 1

3

您只想格式化浮点值以供打印;使用格式:

print "Your tip would be:               {:.2f}".format(tip)
print "Your total bill would be:        {:.2f}".format(totalPrice)

.2f是小数点后 2 位浮点值的格式化迷你语言规范。

您需要删除int()呼叫以保留小数点后的这些数字。你也不需要打电话float()这么多:

MealPrice = float(raw_input("Please type in your bill amount: "))
tip = MealPrice * 0.15
totalPrice = MealPrice + tip

print "Your tip would be:               {:.2f}".format(tip)
print "Your total bill would be:        {:.2f}".format(totalPrice)

演示:

Please type in your bill amount: 42.50
Your tip would be:               6.38
Your total bill would be:        48.88

您也可以进一步调整格式以将这些数字沿小数点对齐。

于 2013-06-13T11:54:26.217 回答