Java - StrictMath round(double x) 方法



描述

Java StrictMath round(double a) 方法返回最接近参数的 long 值。结果通过添加 1/2,取结果的 floor 值,并将结果转换为 long 类型来四舍五入为整数。特殊情况:-

  • 如果参数是 NaN,结果为 0。

  • 如果参数是负无穷大或任何小于或等于 Long.MIN_VALUE 的值,则结果等于 Long.MIN_VALUE 的值。

  • 如果参数是正无穷大或任何大于或等于 Long.MAX_VALUE 的值,则结果等于 Long.MAX_VALUE 的值。

声明

以下是 java.lang.StrictMath.round() 方法的声明

public static long round(double a)

参数

a − 要舍入为 long 的浮点值。

返回值

此方法返回参数舍入到最接近的 long 值的结果。

异常

示例:获取正双精度值的舍入 long 值

以下示例演示了如何使用 StrictMath round() 方法为正双精度值获取 long 值。

package com.tutorialspoint;
public class StrictMathDemo {
   public static void main(String[] args) {

      // get a double number
      double x = 1654.9874;

      // find the closest long for this double number
      System.out.println("StrictMath.round(" + x + ")=" + StrictMath.round(x));
   }
}

输出

让我们编译并运行上面的程序,这将产生以下结果:

StrictMath.round(1654.9874)=1655

示例:获取负双精度值的舍入 long 值

以下示例演示了如何使用 StrictMath round() 方法为负双精度值获取 long 值。

package com.tutorialspoint;
public class StrictMathDemo {
   public static void main(String[] args) {

      // get a double number
      double x = -9765.134;

      // find the closest long for this double number
      System.out.println("StrictMath.round(" + x + ")=" + StrictMath.round(x));
   }
}

输出

让我们编译并运行上面的程序,这将产生以下结果:

StrictMath.round(-9765.134)=-9765

示例:获取零双精度值的舍入 long 值

以下示例演示了如何使用 StrictMath round() 方法为零双精度值获取 long 值。

package com.tutorialspoint;
public class StrictMathDemo {
   public static void main(String[] args) {

      // get double numbers
      double x = -0.0;
      double y = 0.0;	  

      // find the long for these double number
      System.out.println("StrictMath.round(" + x + ")=" + StrictMath.round(x));
	  System.out.println("StrictMath.round(" + y + ")=" + StrictMath.round(y));
   }
}

输出

让我们编译并运行上面的程序,这将产生以下结果:

StrictMath.round(-0.0)=0
StrictMath.round(0.0)=0
java_lang_strictmath.htm
广告
© . All rights reserved.