簡體   English   中英

在Java中添加小數位(3個小數位)

[英]Adding Decimal Places (3 Decimal Places) in Java

我想知道如何在以下程序中將avg舍入到小數點后三位:

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

使用String.format將您的輸出格式化為3個小數位。 輸出是四舍五入的。

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

零數是您要舍入到的小數位數:

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

如果必須將數字四舍五入以用於輸出,則可以使用printf

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

您必須使用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"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM