Java Math rint()方法返回最接近指定值且等于數(shù)學(xué)整數(shù)的值。
也就是說,如果指定值為5.8,則等于數(shù)學(xué)整數(shù)的最接近值是6.0。而對于值5.4,等于數(shù)學(xué)整數(shù)的最接近值是5.0。
rint()方法的語法為:
Math.rint(double value)
注意:rint()方法是靜態(tài)方法。因此,我們可以使用類名Math直接調(diào)用該方法。
arg - 返回其最接近值等于數(shù)學(xué)整數(shù)的參數(shù)
返回最接近的值,arg值等于數(shù)學(xué)整數(shù)
class Main { public static void main(String[] args) { // Math.rint() //小數(shù)點(diǎn)后的值大于5 System.out.println(Math.rint(1.878)); // 2.0 //小數(shù)點(diǎn)后的值小于5 System.out.println(Math.rint(1.34)); // 1.0 //小數(shù)點(diǎn)后的值等于5 System.out.println(Math.rint(1.5)); // 2.0 //小數(shù)點(diǎn)后等于5的值 System.out.println(Math.rint(2.5)); // 2.0 } }
在上面的示例中,請注意兩個表達(dá)式,
// 返回 2.0 Math.rint(1.5) // 返回 2.0 Math.rint(2.5)
在這兩種情況下,小數(shù)點(diǎn)后的值均等于5。然而,
對于1.5 - 方法是向上四舍五入。
對于2.5 - 方法是向下四舍五入。
這是因?yàn)樵?.5 的情況下,rint()方法四舍五入到最接近的偶數(shù)值。因此,在兩種情況下,該方法均舍入為2.0。