Java Math round() 使用方法及示例
Java Math round()方法将指定的值四舍五入为最接近的int或long值,然后将其返回。
也就是说,1.2四舍五入为1,1.8四舍五入为2。
round()方法的语法为:
Math.round(value)
注意:round()是静态方法。因此,我们可以使用类名Math来访问该方法。
round()参数value -要四舍五入的数字
注意:该值的数据类型应为float或double。
round()返回值如果参数为float,则返回int值
如果参数为double,则返回long值
round()方法:如果小数点后的值大于或等于5,则向上舍入
1.5 => 2
1.7 => 2
如果小数点后的值小于5,则向下舍入
1.3 => 1
示例1:Java Math.round()与double
示例
class Main {
public static void main(String[] args) {
// Math.round()方法
//小数点后的值大于5
double a = 1.878;
System.out.println(Math.round(a)); // 2
//小数点后的值等于5
double b = 1.5;
System.out.println(Math.round(b)); // 2
//小数后值小于5
double c = 1.34;
System.out.println(Math.round(c)); // 1
}
}
示例2:带有float的Java Math.round()
示例
class Main {
public static void main(String[] args) {
// Math.round()方法
//小数点后的值大于5
float a = 3.78f;
System.out.println(Math.round(a)); // 4
//小数点后的值等于5
float b = 3.5f;
System.out.println(Math.round(b)); // 4
// 小数后值小于5
float c = 3.44f;
System.out.println(Math.round(c)); // 3
}
}
推荐的教程