跳到主要内容

Java Math round() 方法

round() 方法将指定值四舍五入到最接近的整数或长整数并返回。也就是说,3.87 四舍五入为 43.24 四舍五入为 3

示例

class Main {
public static void main(String[] args) {

double a = 3.87;
System.out.println(Math.round(a));

}
}

// 输出:4

Math.round() 的语法

round() 方法的语法是:

Math.round(value)

这里,round() 是一个静态方法。因此,我们通过类名 Math 来访问这个方法。

round() 参数

round() 方法接受一个参数。

  • value - 需要四舍五入的数值

注意:数值的数据类型应该是 floatdouble

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:Java Math.round() 使用 float

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

}
}

推荐教程