Rounding to 2 decimal places in python gpa calculator

For my assignment, I have been asked to create a GPA calculator. They want me to edit my code to make the GPA output always show two decimal places. However, mine doesn't seem to be working! D:

The output only prints to 1 decimal place

here is what I've tried so far, ive also tried str instead of float:

gpa = total/num_of_subjects #using this formula the gpa is calculated
gpa = float(round(gpa, 2))

print (gpa) #output gpa

Upvotes: 1

Views: 374

Answers (4)

Deck451
Deck451

Reputation: 61

Try formatting it to only display 2 decimals

gpa = total / num_of_subjects
print(f"{gpa:.2f}")

Upvotes: 2

João Bentes
João Bentes

Reputation: 44

from decimal import Decimal


total = 109

num_of_subjects = 33
gpa = total/num_of_subjects #using this formula the gpa is calculated
gpcc= Decimal(gpa)
print(round(gpcc,2))

here u have a simplieer solution to the same problem! cheers!

Upvotes: -1

Lonely Dreamer
Lonely Dreamer

Reputation: 44

You need to use int in order for it to round up and not down. The other problem with your code was that you were using num_of_subjects as an input but then trying to divide by it. So if someone entered 3 subjects their gpa would come out at 0.0. Here's how you should fix it:

def calculateGPA():

total = float(input("Enter the number of units completed"))

num_of_subjects = float(input("Enter the number of courses taken"))

gpa = total / num_of_subjects

print ("The GPA is", gpa)

if gpa >= 4.0:

print ("Excellent")

elif gpa > 3.5 and <4.0:

print ("Very Good")

else :

print ("Good")

calculateGPA()

Upvotes: -1

Cardstdani
Cardstdani

Reputation: 5223

You can format the output as a string value with "{:0.2f}" format, so your answer will always have 2 decimal digits despite gpa value:

total, num_of_subjects = 100, 10

gpa = total/num_of_subjects
gpa = float(round(gpa, 2))

print("{:0.2f}".format(gpa))

10.00

Upvotes: 1

Related Questions