2016-12-10 14 views
-1

如何將2.50添加到成本中?添加一個帶有2位小數的數字給變量(2.50)

現在,它只是打印出來爲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

有兩個問題:

  • 你,只要你將它轉換爲intint(current)鬆小數。
  • 如果你總是想要兩位小數,你必須使用某種字符串格式。

我會建議只使用str.format「2」位數(由.2f這裏執行):

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

如果您與「錢」的工作樣的變量,你應該使用decimal.Decimal而不是浮點數,這樣你就不需要關心浮點數的「不精確性」。

2

您正在轉換您的浮充電流賬單金額在這一行

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

到int,而不是使用此命令打印當前的法案量。

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))