语法:
public static long round(double d); public static int round(float f);
round()方法round()方法在java.lang包中可用。
round(double d)方法用于将最接近的long值返回给定参数。
round(float f)方法用于将最接近的int值返回给定参数,并通过加½将其舍入为整数并将结果从float转换为int。
这些方法不会引发异常。
这些是静态方法,可以使用类名进行访问,如果尝试使用类对象访问这些方法,则不会出现任何错误。
参数:
float / double –表示要取整的值。
返回值:
此方法的返回类型为int / long-它根据给定的参数类型返回舍入的值。
注意:
如果传递NaN,则该方法返回0。
如果我们传递一个负无穷大,则该方法返回Long.MIN_VALUE。
如果我们传递一个正无穷大,则该方法返回Long.MAX_VALUE。
如果我们传递的值小于或等于Integer.MIN_VALUE / Long.MIN_VALUE,则该方法返回Integer.MIN_VALUE / Long.MIN_VALUE。
如果传递的值大于或Integer.MAX_VALUE / Long.MAX_VALUE,则该方法返回Integer.MAX_VALUE / Long.MAX_VALUE。
示例
//Java程序演示示例
//round()StrictMath类的方法
public class Round {
public static void main(String[] args) {
//变量声明
double d1 = -1.0 / 0.0;
double d2 = 1.0 / 0.0;
double d3 = 1234.56;
double d4 = 1234.42;
float f1 = -1.0f / 0.0f;
float f2 = 1.0f / 0.0f;
float f3 = 1234.56f;
float f4 = 1234.42f;
System.out.println();
System.out.println("round(double): ");
//在这里,我们将得到(Long.MIN_VALUE),我们
//传递参数,其值为(-Infinity)
System.out.println("StrictMath.round (d1): " + StrictMath.round(d1));
//在这里,我们将得到(Long.MAX_VALUE),我们
//传递参数,其值为(Infinity)
System.out.println("StrictMath.round (d2): " + StrictMath.round(d2));
//在这里,我们将得到(1235)并且我们
//传递参数,其值为(1234.56)
System.out.println("StrictMath.round (d3): " + StrictMath.round(d3));
//在这里,我们将得到(1234)并且我们正在传递
//参数的值为(1234.12)
System.out.println("StrictMath.round (d4): " + StrictMath.round(d4));
System.out.println();
System.out.println("round(float): ");
//在这里,我们将得到(Integer.MIN_VALUE),我们
//传递参数,其值为(-Infinity)
System.out.println("StrictMath. round (f1): " + StrictMath.round(f1));
//在这里,我们将得到(Integer.MAX_VALUE),并且我们
//传递参数,其值为(Infinity)
System.out.println("StrictMath. round (f2): " + StrictMath.round(f2));
//在这里,我们将得到(1235)并且我们
//传递参数,其值为(1234.56)
System.out.println("StrictMath. round (f3): " + StrictMath.round(f3));
//在这里,我们将得到(1234)并且我们
//传递参数,其值为(1234.12)
System.out.println("StrictMath. round (f4): " + StrictMath.round(f4));
}
}输出结果
round(double): StrictMath.round (d1): -9223372036854775808 StrictMath.round (d2): 9223372036854775807 StrictMath.round (d3): 1235 StrictMath.round (d4): 1234 round(float): StrictMath. round (f1): -2147483648 StrictMath. round (f2): 2147483647 StrictMath. round (f3): 1235 StrictMath. round (f4): 1234