Java - Math round(double x) 方法



描述

Java Math round(double a) 方法返回最接近引數的 long 值。結果透過新增 1/2,取結果的 floor 值,並將結果強制轉換為 long 型別來四捨五入到整數。特殊情況:-

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

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

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

宣告

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

public static long round(double a)

引數

a − 要四捨五入到 long 的浮點值。

返回值

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

異常

示例:獲取正 double 值的四捨五入的 long 值

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

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

輸出

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

Math.round(1654.9874)=1655

示例:獲取負 double 值的四捨五入的 long 值

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

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

輸出

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

Math.round(-9765.134)=-9765

示例:獲取零 double 值的四捨五入的 long 值

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

package com.tutorialspoint;
public class MathDemo {
   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("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
廣告