0

私は Python 2.7x を学ぼうとしている (2 週間くらい) 初心者です。ユーザーが食事の費用を入力し、.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

float 値を印刷専用にフォーマットしたい。フォーマットを使用:

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 に答える