一般而言,所有程式語言和計算機都無法處理無限數。數字的捨入和修整幾乎無所不在,因為現代電腦的本質就是這樣。Java 語言有一個特殊的數學運算類別 — Math,它有一個方法可以讓您按照我們需要的方式對數字進行舍入。這裡我們有Math.round()方法,在本文中我們將解釋如何使用它。
Math.round() 語法
java.lang.Math.round()是一種數學方法,傳回與其參數最接近的長整數或整數。Java Math round()的結果透過加 1/2 並取加 1/2 後的結果取整數來四捨五入為整數。執行此操作後,數字將轉換為 long 或 int 類型。round() 方法的語法為:Math.round(value)
round()就像大多數Math類別方法一樣是靜態的。值參數可以是浮點型或雙精度型。此方法將最接近的 int(如果是 float 值)或 long(如果是 double 值)數字傳回參數,並四捨五入到正無窮大。
Math.round() 的特殊情況
-
如果參數為 NaN,則結果將為 0。
-
如果參數為負無窮大或小於或等於Integer.MIN_VALUE值的任何值,則結果將為Integer.MIN_VALUE值。
-
如果參數為正無窮大或任何大於或等於Integer.MAX_VALUE值的值,則結果等於Integer.MAX_VALUE值。
Java Math.round() 範例
讓我們編寫一個程序,並使用不同參數(float 和 double)的範例來示範 Math round()方法。public class MathExample {
//java.lang.Math.round() method example with float and double arguments
public static void main(String[] args) {
double e = 2.71828;
float pi = 3.1415f;
//Math.round() method: float turns to int
int intOfPi = Math.round(pi);
//Math.round() method: double turns to long
long intOfE = Math.round(e);
System.out.println("integer part of pi = " + intOfPi);
System.out.println("integer part of e = " + intOfE);
}
}
該程式的輸出是:
pi 的整數部分 = 3 e 的整數部分 = 3
如您所見,其中一個數字已向上舍入,另一個數字已向下舍入為較小的整數。在這兩種情況下,結果都是最接近的整數。這就是Java.lang.Math.round()方法的工作原理。
GO TO FULL VERSION