round()
方法将指定值四舍五入到最接近的 int 或 long 值并返回它。也就是说,3.87 四舍五入为 4,3.24 四舍五入为 3。
示例
class Main {
public static void main(String[] args) {
double a = 3.87;
System.out.println(Math.round(a));
}
}
// Output: 4
Math.round() 的语法
round()
方法的语法是
Math.round(value)
这里,round()
是一个静态方法。因此,我们使用类名 Math
来访问该方法。
round() 参数
round()
方法接受一个参数。
- value - 要四舍五入的数字
注意: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() method
// value greater than 5 after decimal
double a = 1.878;
System.out.println(Math.round(a)); // 2
// value equals to 5 after decimal
double b = 1.5;
System.out.println(Math.round(b)); // 2
// value less than 5 after decimal
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() method
// value greater than 5 after decimal
float a = 3.78f;
System.out.println(Math.round(a)); // 4
// value equals to 5 after decimal
float b = 3.5f;
System.out.println(Math.round(b)); // 4
// value less than 5 after decimal
float c = 3.44f;
System.out.println(Math.round(c)); // 3
}
}
另请阅读