簡體   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