dimanche 24 février 2019

How do I only get 2 decimals when printing a double?

I have 2 questions that connect to each other.
1) I am working on a project where I need to add the gpa of 4 students to find the average. The gpa can only go to two decimal places when printed out, but I have not been able to figure out what's wrong with my code. Or find another simpler way to print out the answer. 2) Every time I click on the buttons for the student gpa it's supposed to change and be recalculated, same should happen to the average. It will do that but if I myself add the gpa's of the students and divide by four the average gpa is no where near where it should be and I don't understand why that is happening. This code is from my group.java class that calculates the average gpa

double averageGPA()
{
    double average = (sd1.GPA + sd2.GPA + sd3.GPA + sd4.GPA) / 4;
    return Double.toString("%.2f", average);// Double.format("%.2f", average) does not work either
}

This is my code from student.java class that calculates the 4 gpa's randomly.

 String getInfo()
{
   GPA = Math.random();
   myRandomNumber = (GPA *4.0);
   return "NAME = " + firstName + " " + lastName + " " + String.format("%.2f", myRandomNumber);

}

an example of when the I run the code: student 1: 2.34 student 2: 0.19 student 3: 2.66 Student 4: 2.94 Average = .5079037

when the actual average should be 2.03




Aucun commentaire:

Enregistrer un commentaire