Java - Math round(float x) 方法



描述

java.lang.Math.round(float a) 方法返回最接近引數的 int 值。結果透過加上 1/2,取結果的 floor,並將結果強制轉換為 int 型別來四捨五入為整數。特殊情況 -

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

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

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

宣告

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

public static int round(float a)

引數

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

返回值

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

異常

示例:獲取正浮點值的四捨五入後的 int 值

以下示例顯示了使用 Math round() 方法為正浮點值獲取 long 值。

package com.tutorialspoint;
public class MathDemo {
   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("Math.round(" + x + ")=" + Math.round(x));
   }
}

輸出

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

Math.round(1654.9874)=1655

示例:獲取負浮點值的四捨五入後的 int 值

以下示例顯示了使用 Math round() 方法為負浮點值獲取 long 值。

package com.tutorialspoint;
public class MathDemo {
   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("Math.round(" + x + ")=" + Math.round(x));
   }
}

輸出

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

Math.round(-9765.134)=-9765

示例:獲取零浮點值的四捨五入後的 int 值

以下示例顯示了使用 Math round() 方法為零浮點值獲取 long 值。

package com.tutorialspoint;
public class MathDemo {
   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("Math.round(" + x + ")=" + Math.round(x));
	  System.out.println("Math.round(" + y + ")=" + Math.round(y));
   }
}

輸出

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

Math.round(-0.0)=0
Math.round(0.0)=0
java_lang_math.htm
廣告

© . All rights reserved.