[英]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: 有两个问题:
int
in int(current)
. int(current)
中的int(current)
转换为int
,立即释放小数位。 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.