Format the total so it does not show decimal places

Viewed 39

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)
4 Answers

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
Related