Java - StrictMath round(float x) 方法



描述

java.lang.StrictMath.round(float a) 方法返回最接近引數的 int 值。結果透過新增 1/2、取結果的底並將其轉換為 int 型別來四捨五入為整數。特殊情況 -

  • 如果引數為 NaN,則結果為 0。

  • 如果引數為負無窮大或任何小於或等於 Integer.MIN_VALUE 的值,則結果等於 Integer.MIN_VALUE 的值。

  • 如果引數為正無窮大或任何大於或等於 Integer.MAX_VALUE 的值,則結果等於 Integer.MAX_VALUE 的值。

宣告

以下是 java.lang.StrictMath.round() 方法的宣告

public static int round(float a)

引數

a - 要四捨五入為整數的浮點值。

返回值

此方法返回引數四捨五入到最接近的 int 值的結果。

異常

示例:獲取正浮點值的四捨五入整數

以下示例演示瞭如何使用 StrictMath round() 方法獲取正浮點值的 long 值。

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

      // get a float number
      float x = 1654.9874f;

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

輸出

讓我們編譯並執行上述程式,這將產生以下結果 -

StrictMath.round(1654.9874)=1655

示例:獲取負浮點值的四捨五入整數

以下示例演示瞭如何使用 StrictMath round() 方法獲取負浮點值的 long 值。

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

      // get a float number
      float x = -9765.134f;

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

輸出

讓我們編譯並執行上述程式,這將產生以下結果 -

StrictMath.round(-9765.134)=-9765

示例:獲取零浮點值的四捨五入整數

以下示例演示瞭如何使用 StrictMath round() 方法獲取零浮點值的 long 值。

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

      // get float numbers
      float x = -0.0f;
      float y = 0.0f;	  

      // find the long for these float 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
廣告