繁体   English   中英

格式化总数,使其不显示小数位

[英]Format the total so it does not show decimal places

所以,我试图让这段代码最后不显示任何小数位(总计)......但我真的找不到办法做到这一点。 有没有办法在不必重写所有内容的情况下做到这一点?


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)

您可以将total转换为整数:

total = int(total)

例如:

total = 3.75
total = int(total)
print(total) # 3

由于您的每个输入都是浮点数,因此您的“总计”也将是浮点数。 如果您希望“总计”没有任何小数点,则应在打印前将总计转换为整数: int(total)

您还可以使用 round 函数对结果进行四舍五入

例子:

round(total)

您可以使用 f 字符串来完成此操作。 F-strings 允许你用字符串插入 python 表达式,这意味着你可以把你的变量放在那里:

>>> total = 3.75
>>> print(f"The total is: {total}")
The total is: 3.75

它还允许格式化语法,这意味着我们可以通过在冒号后指定浮点格式.0f来将浮点数限制为没有小数位。

>>> total = 3.75
>>> print(f"The total is: {total:.0f}")
The total is: 4

暂无
暂无

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

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