Java Math round()方法將指定的值四舍五入為最接近的int或long值,然后將其返回。
也就是說,1.2四舍五入為1,1.8四舍五入為2。
round()方法的語法為:
Math.round(value)
注意:round()是靜態(tài)方法。因此,我們可以使用類名Math來訪問該方法。
value -要四舍五入的數(shù)字
注意:該值的數(shù)據(jù)類型應(yīng)為float或double。
如果參數(shù)為float,則返回int值
如果參數(shù)為double,則返回long值
round()方法:
如果小數(shù)點后的值大于或等于5,則向上舍入
1.5 => 2 1.7 => 2
如果小數(shù)點后的值小于5,則向下舍入
1.3 => 1
class Main {
public static void main(String[] args) {
// Math.round()方法
//小數(shù)點后的值大于5
double a = 1.878;
System.out.println(Math.round(a)); // 2
//小數(shù)點后的值等于5
double b = 1.5;
System.out.println(Math.round(b)); // 2
//小數(shù)后值小于5
double c = 1.34;
System.out.println(Math.round(c)); // 1
}
}class Main {
public static void main(String[] args) {
// Math.round()方法
//小數(shù)點后的值大于5
float a = 3.78f;
System.out.println(Math.round(a)); // 4
//小數(shù)點后的值等于5
float b = 3.5f;
System.out.println(Math.round(b)); // 4
// 小數(shù)后值小于5
float c = 3.44f;
System.out.println(Math.round(c)); // 3
}
}