在Java中添加小数位数(3个小数位)

时间:2014-04-25 20:51:03

标签: java rounding

我想知道如何在以下程序中将avg舍入到小数点后3位:

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

4 个答案:

答案 0 :(得分:3)

使用String.format将输出格式化为3位小数。输出是四舍五入的。

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

答案 1 :(得分:0)

零的数量是要舍入的小数位数:

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

答案 2 :(得分:0)

如果必须对输出进行舍入,则可以使用printf来完成:

System.out.printf("Your average for the game or season is: %.3f%n", avg);

答案 3 :(得分:0)

您必须使用DecimalFormat类来使用模式格式化您的号码。

你可以这样做:

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

格式化数字的另一种方法是使用String.format,如下所示:

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