[英]Format the total so it does not show decimal places
So, I'm trying to make this code not show any decimal places in the end (total)... But I can't really find a way to do it.所以,我试图让这段代码最后不显示任何小数位(总计)......但我真的找不到办法做到这一点。 Is there a way to do it without having to rewrite everything?
有没有办法在不必重写所有内容的情况下做到这一点?
test1_weight = float(input("Type your 1st Test weight: "))
test2_grade = float(input("Type your 1st Test grade: "))
test2_weight = float(input("Type your 1st Test weight: "))
total = (test1_grade * test1_weight + test2_grade * test2_weight)/(test1_weight + test2_weight)
print ("The weighted average is: ", total)
You can cast total
to an integer:您可以将
total
转换为整数:
total = int(total)
For example:例如:
total = 3.75
total = int(total)
print(total) # 3
Since each of your inputs are floats, your 'total' will also be a float.由于您的每个输入都是浮点数,因此您的“总计”也将是浮点数。 If you want the 'total' to not have any decimal points, you should cast total to an integer before printing:
int(total)
如果您希望“总计”没有任何小数点,则应在打印前将总计转换为整数:
int(total)
You can also round the result with the round function您还可以使用 round 函数对结果进行四舍五入
Exemple:例子:
round(total)
You can accomplish this with f-strings.您可以使用 f 字符串来完成此操作。 F-strings allow you to interpolate python expressions with strings, meaning you can stick your variable right in there:
F-strings 允许你用字符串插入 python 表达式,这意味着你可以把你的变量放在那里:
>>> total = 3.75
>>> print(f"The total is: {total}")
The total is: 3.75
It also allows for formatting syntax, which means we can restrict the float to no decimal places by specifying the float format .0f
after a colon.它还允许格式化语法,这意味着我们可以通过在冒号后指定浮点格式
.0f
来将浮点数限制为没有小数位。
>>> total = 3.75
>>> print(f"The total is: {total:.0f}")
The total is: 4
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.