在Java中,Math.round()
函數用于執行四舍五入操作。對于小數,這個函數會將其四舍五入到最接近的整數。具體來說,它會根據小數部分是大于或等于0.5還是小于0.5來進行舍入。
以下是一些示例:
System.out.println(Math.round(11.5)); // 輸出 12
System.out.println(Math.round(10.4)); // 輸出 10
System.out.println(Math.round(10.6)); // 輸出 11
需要注意的是,Math.round()
函數接受一個float
或double
類型的參數,并返回一個long
(如果參數是float
)或int
(如果參數是double
)類型的結果。因此,如果你想要保留舍入后的小數部分,你可能需要將結果轉換回float
或double
類型。
例如:
double num = 10.6;
long roundedNum = Math.round(num);
double roundedNumWithDecimal = (double) roundedNum;
System.out.println(roundedNumWithDecimal); // 輸出 11.0