Adding Decimal Places (3 Decimal Places) in Java

寵の児 提交于 2020-05-17 16:45:10

问题


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);
    }
}

回答1:


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



回答2:


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"



回答3:


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

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



回答4:


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


来源:https://stackoverflow.com/questions/23302785/adding-decimal-places-3-decimal-places-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!