简体   繁体   English

向变量加一个小数点后两位的数字(2.50)

[英]Adding a number with 2 decimal places to a variable (2.50)

How do I add 2.50 to the cost? 如何将费用增加2.50?

Right now it just prints it out as 2. 现在,它只是将其打印为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)))

There are two problems: 有两个问题:

  • You loose the decimal places as soon as you convert it to an int in int(current) . int(current)中的int(current)转换为int ,立即释放小数位。
  • If you always want two decimal places you have to use some sort of string formatting. 如果您始终想要两位小数,则必须使用某种字符串格式。

I would advise just to use str.format with "2" decimal places (here enforced by the .2f ): 我建议仅将str.format与小数点后两位(由.2f强制使用)一起使用:

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

If you're working with "money"-like variables you should use decimal.Decimal instead of floats, just so you don't need to take care of the "inexactness" of floating point numbers. 如果您正在使用decimal.Decimal “ money”的变量,则应使用decimal.Decimal而不是float,只是这样,您就不必担心浮点数的“ inxactness”。

You are converting your float current bill amount to int in this line 您正在此行中将当前浮动帐单金额转换为int

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

Instead use this command to print your current bill amount. 而是使用此命令来打印您当前的帐单金额。

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

output 输出

Your current total cost is £5.50

int turns a number into a whole number. int将数字转换为整数。 For example, int(2.1) = 2 例如, int(2.1) = 2

Your last line should have just str(current) . 您的最后一行应该只有str(current)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM