如何在 Java 中四捨五入
Rupam Yadav
2023年10月12日
Java
Java Number
本文將介紹如何使用 Java 中的原生類對任何數字進行四捨五入。我們將使用 Java 中 Math 類的 ceil() 方法。
Math 有一些方法,如 Math.floor() 和 Math.ceil() 來對數字進行四捨五入。Math.ceil() 用於四捨五入,這就是為什麼我們要使用它。
我們的目標是將給定的數字四捨五入。讓我們舉個例子,如果我們有一個數字 0.2,那麼取整後的數字將是 1。
Math.ceil() 將任何數字取整到整數
Math.ceil() 取一個雙精度值,然後四捨五入。在下面的例子中,a 的值是 0.06,四捨五入到 1.0。
我們希望結果是一個整數,但是當我們使用 Math.ceil() 時,我們得到的結果是一個 double;這就是為什麼我們要將結果轉為 int。
例子:
public class Main {
public static void main(String[] args) {
double a = 0.06;
int roundedNumA = (int) Math.ceil(a / 100);
System.out.println("Rounding up " + a + " we get " + roundedNumA);
}
}
輸出:
Rounding up 0.6 we get 1
Math.ceil() 四捨五入一個浮點數
我們可以使用 Math.ceil() 方法將浮點數四捨五入。
例子:
public class Main {
public static void main(String[] args) {
float a = 12.34f;
System.out.println("Rounding up " + a + " we get " + Math.ceil(a));
}
}
輸出:
Rounding up 12.34 we get 13.0
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Rupam Yadav
Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.
LinkedIn