在 Java 中添加小数位(3 个小数位) [英] Adding Decimal Places (3 Decimal Places) in Java
本文介绍了在 Java 中添加小数位(3 个小数位)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道如何使以下程序中的 avg
四舍五入到小数点后三位:
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);
}
}
推荐答案
使用 String.format
将您的输出格式化为 3 个小数位.输出四舍五入.
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));
这篇关于在 Java 中添加小数位(3 个小数位)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文