java.lang.Math.round()是内置数学函数,它返回最接近参数的long。通过将1/2相加,将结果四舍五入为整数,再加上1/2后取结果的下限,并将结果强制转换为long类型。
如果参数为NaN,则结果为0。
如果参数为负无穷大或任何小于或等于Integer.MIN_VALUE的值,则结果等于Integer.MIN_VALUE的值。
如果参数为正无穷大或任何大于或等于Integer.MAX_VALUE的值,则结果等于Integer.MAX_VALUE的值。
用法:
public static int round(float val)
Parameter:
val - floating-point value to be rounded to an integer.
返回值:
该方法返回四舍五入到最接近的int值的参数值。
例:演示java.lang.Math.round()函数的工作
// Java program to demonstrate working
// of java.lang.Math.round() method
import java.lang.Math;
class Gfg {
// driver code
public static void main(String args[])
{
// float numbers
float x = 4567.9874f;
// find the closest int for these floats
System.out.println(Math.round(x));
float y = -3421.134f;
// find the closest int for these floats
System.out.println(Math.round(y));
double positiveInfinity = Double.POSITIVE_INFINITY;
// returns the Integer.MAX_VALUE value when
System.out.println(Math.round(positiveInfinity));
}
}
输出:
4568
-3421
9223372036854775807