简体   繁体   中英

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 = 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)

You can also round the result with the round function

Exemple:

round(total)

You can accomplish this with f-strings. F-strings allow you to interpolate python expressions with strings, meaning you can stick your variable right in there:

>>> 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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