Question

I was wondering how to make avg in the following program round to 3 decimal places:

public class BaseballCalculator {
    public static void main(String args[])  {
        Scanner myScanner = new Scanner(System.in);
        double atBats;
        double baseHits;
        double onBase;
        double avg;
        double onBasePercentage;

        System.out.println("How many atbats did you have? ");
            atBats = myScanner.nextDouble();

        System.out.println("How many base hits and homeruns did you have? ");
            baseHits = myScanner.nextDouble();

        System.out.println("How many times did you get a hit by pitch or walk? ");
            onBase = myScanner.nextDouble();

        avg = baseHits / atBats;
        onBasePercentage = (baseHits + onBase) / atBats;

        System.out.println("You have a total of " + baseHits + " base hits for the season");
        System.out.println("You have a total of " + atBats + " at bats for the season");
        System.out.println("Your average for the game or season is: " + avg);
        System.out.println("Your on base percentage for the game or year is: " + onBasePercentage);
    }
}
Was it helpful?

Solution

Use String.format to format your output to 3 decimal places. The output is rounded.

System.out.println("Your average for the game or season is: " +
    String.format("%.3f", avg));

OTHER TIPS

You have to user DecimalFormat class to format your number using a pattern.

You can do this:

DecimalFormat df = new DecimalFormat("#.000");
String average = df.format(avg); // double 3.0 will be formatted as string "3.000" 

Another way to format a number is using the String.format, like this:

String average = String.format("%.1f", avg); // average = "5.0"

The number of zeroes is the number of decimal places you want to round to:

double avg = ((int) (1000 * Math.round(avg))) / 1000;

If the number has to be rounded just for output, you can do it by using printf:

System.out.printf("Your average for the game or season is: %.3f%n", avg);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top