2016-12-10 9 views
-1

コストに2.50を追加するにはどうすればよいですか?変数に小数点以下2桁の数値を追加する(2.50)

は今のところそれはちょうどあなたの代わりにあなたの現在の法案を印刷するには、このコマンドを使用して、この行

print("Your current total cost is " + "£" + str(int(current))) 

でintにあなたのフロート現在の請求額を変換する2.

cost = 0.00 

r = open("toppings.txt") 

bases = ["small","medium","large"] 

toppings = ["Pepperoni","Chicken","Cajun Chicken","Mushrooms", 
      "Red Onions","Sweetcorn","Ham","Cheese","Spicy Minced Beef", 
      "Anchovies","Tuna","Peppers","Jalapenos","Green Chillies"] #0-13 

def small(): 

    current = cost + 2.50 

    print("Your current total cost is " + "£" + str(int(current))) 
+0

int(current)を削除し、str(current)を直接使用します。 –

+5

int() – DZDomi

+0

'print("あなたの現在の総コストは£%2f "%current"です。 – Bodhi94

答えて

3

二つの問題があります。

  • あなたはできるだけ早くあなたがint(current)intに変換して小数点以下を失うが。
  • 小数点以下2桁が常に必要な場合は、何らかの文字列書式を使用する必要があります。

私は(ここでは.2fによって強制)「2」小数点以下でstr.formatを使用するように助言する:

'Your current total cost is £ {:.2f} '.format(current) 

あなたは変数様「お金」で作業している場合は、decimal.Decimalを使用する必要があります浮動小数点数の「不正確さ」を気にする必要はありません。

2

としてそれをプリントアウト量。

print("Your current total cost is " + "£" + "{0:.2f}".format(round(current,2))) 

出力

Your current total cost is £5.50 
0
int

は整数に番号を回します。たとえば、int(2.1) = 2

最後の行はちょうどstr(current)である必要があります。

print("Your current total cost is " + "£" + str(current)) 
関連する問題