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
廣告