Home > Software engineering >  Rounding to 2 decimal places in python gpa calculator
Rounding to 2 decimal places in python gpa calculator

Time:07-04

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

CodePudding user response:

Try formatting it to only display 2 decimals

gpa = total/num_of_subjects #using this formula the gpa is calculated
print(f"{gpa:.2f}")

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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!

  • Related