user3316886
user3316886

Reputation: 83

Rounding in double java

public class project3 {
    public static void main(String[] args) {

        int earnedRuns = 52;
        int inningsPitched = 182;
        double ERA = (earnedRuns * 9) / inningsPitched;
        String FirstName = "Anibal";
        String LastName = "Sanchez";

        System.out.println("Pitcher's first name: " + FirstName);
        System.out.println("Pitcher's last name: " + LastName);
        System.out.println("Number of earned runs: " + earnedRuns);
        System.out.println("Number of innings pitched: " + inningsPitched);
        System.out.println(FirstName + " " + LastName + " has an ERA of " + ERA);
    }
}

The ERA comes out as 2.0 not 2.57... ect I cannot figure out why

Upvotes: 2

Views: 178

Answers (1)

maxammann
maxammann

Reputation: 1048

Baically you're:

  1. multiplying an integer by an integer -> integer (Result: 486)
  2. dividing an integer by an integer -> integer (Result: 2)
  3. Assign the result to an double variable -> double (Result: 2.0D)

So you first need to cast ("convert") those integers to floats or doubles.

double ERA = ((double)earnedRuns * 9) / inningsPitched;

or simpler:

double ERA = (earnedRuns * 9.0) / inningsPitched;

It's enough to cast just one integer because in java: integer * double -> double

EDIT:

The 9.0 D or 9.0 d just tells java that explicitly that 9.0 is meant to be a double. The same also works for 9.0 f or 9.0 F. This means that 9.0 is a float.

Upvotes: 4

Related Questions