如何在成本中添加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 :(得分:3)
有两个问题:
int(current)
转换为int
时,您会丢失小数位。我建议只使用带有“2”小数位的str.format
(此处由.2f
强制执行):
'Your current total cost is £ {:.2f} '.format(current)
如果你正在处理类似“钱”的变量,你应该使用decimal.Decimal
而不是浮点数,这样你就不需要处理浮点数的“不精确性”。
答案 1 :(得分:2)
您正在将此浮动当前账单金额转换为此行中的int
print("Your current total cost is " + "£" + str(int(current)))
而是使用此命令打印您当前的账单金额。
print("Your current total cost is " + "£" + "{0:.2f}".format(round(current,2)))
输出
Your current total cost is £5.50
答案 2 :(得分:0)
int
将数字转换为整数。例如,int(2.1) = 2
你的最后一行应该只有str(current)
。
print("Your current total cost is " + "£" + str(current))