向变量中添加小数点后两位的数字(2.50)

2024-05-15 23:24:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我该怎么加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)))

Tags: txtredopencurrentsmall费用mediumlarge
3条回答

int把一个数变成一个整数。例如,int(2.1) = 2

最后一行应该只有str(current)。你知道吗

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

有两个问题:

  • 一旦将其转换为int(current)中的^{},小数位数就会丢失。你知道吗
  • 如果你总是想要两个小数位,你必须使用一些字符串格式。你知道吗

我建议只使用带“2”小数位的^{}(这里由.2f强制执行):

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

如果您使用的是类似于“money”的变量,那么应该使用^{}而不是float,这样您就不需要考虑浮点数的“不精确性”。你知道吗

您正在将此行中的浮动当前账单金额转换为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

相关问题 更多 >