[英]Only need two decimal places in my output
如何獲取小數點后僅兩位數字的double值。 如果我的身高輸入為72體重為170,我收到的輸出將給我BMI = 23.053626543209877。我不確定如何清除.05之后的尾隨數字
這是我的代碼:
import java.util.Scanner;
公共課bmi {
private static Scanner scanner;
public static void main(String[] args) {
// Variables
double height;
double weight;
double bmi;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter your height: ");
height = keyboard.nextDouble();
if(height<=0)
{
System.out.println("That's an invalid height.");
return;
}
System.out.println("Please enter your weight: ");
weight = keyboard.nextDouble();
if(weight<=0)
{
System.out.println("That's an invalid weight.");
return;
}
bmi = calculateBMI(height, weight);
System.out.println("BMI = " + bmi);
System.out.println(bmiDescription(bmi));
keyboard.close();
}
static double calculateBMI (double height, double weight) {
return weight * 703 / (height * height);
}
static String bmiDescription (double bmi) {
if (bmi < 18.5) {
return "You are underweight.";
} else {
if (bmi > 25) {
return "You are overweight.";
} else {
return "You are optimal.";
}
}
}
}
您可以將帶格式的io與printf
,例如
double bmi = 23.053626543209877;
System.out.printf("BMI = %.2f%n", bmi);
輸出(正如我所希望的那樣,甚至可以進行舍入)
BMI = 23.05
在處理數字時,最好始終保持精度,但是在某些情況下,深度精度並不是真正要考慮的問題。 如果要將特定的double數據類型變量設置為特定的十進制精度,則可以將Double類型的值傳遞給這樣的方法:
double bmi = round(23.053626543209877, 2);
System.out.println("BMI = " + bmi);
private static double round(double value, int precision) {
int scale = (int) Math.pow(10, precision);
return (double) Math.round(value * scale) / scale;
}
輸出將是:
BMI = 23.05
就像方法名稱所暗示的那樣,返回的結果也會四舍五入。
這是我使用的一種便捷方法:
public static double round (double value, int precision) {
int scale = (int) Math.pow(10, precision);
return (double) Math.round(value * scale) / scale;
}
只需傳遞您的值,然后傳遞精度(要顯示的小數位數)。
例如: round(2.3891237, 2)
將返回2.39
在calculateBMI()中執行以下操作。
NumberFormat numberFormat = NumberFormat.getIntegerInstance();
numberFormat.setMaximumFractionDigits(2);
numberFormat.format(x);
其中x是您計算出的double值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.