Java - Double compare() 方法



描述

Java Double compare() 方法用於比較兩個指定的雙精度浮點數。返回的整數值的符號與以下呼叫的返回值的符號相同:

new Double(d1).compareTo(new Double(d2))

宣告

以下是 java.lang.Double.compare() 方法的宣告:

public static int compare(double d1, double d2)

引數

  • d1 − 這是要比較的第一個雙精度浮點數。

  • d2 − 這是要比較的第二個雙精度浮點數。

返回值

如果 d1 在數值上等於 d2,則此方法返回 0;如果 d1 在數值上小於 d2,則返回小於 0 的值;如果 d1 在數值上大於 d2,則返回大於 0 的值。

異常

檢查雙精度浮點數是否大於給定雙精度浮點數示例

以下示例演示瞭如何使用 Double compare() 方法來檢查一個值是否大於另一個值。我們有兩個雙精度浮點數,並使用 compare() 方法比較它們,然後將結果與 0 進行比較。如果結果大於 0,則第一個數字大於第二個數字。如果結果小於 0,則第一個數字小於第二個數字。否則,兩個值相同。

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

      // compares the two specified double values
      double d1 = 15.45;
      double d2 = 11.50;
      int retval = Double.compare(d1, d2);
    
      if(retval > 0) {
         System.out.println("d1 is greater than d2");
      } else if(retval < 0) {
        System.out.println("d1 is less than d2");
      } else {
         System.out.println("d1 is equal to d2");
      }
   }
} 

輸出

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

d1 is greater than d2

檢查雙精度浮點數是否小於給定雙精度浮點數示例

以下另一個示例演示瞭如何使用 Double compare() 方法來檢查一個值是否小於另一個值。我們有兩個雙精度浮點數,並使用 compare() 方法比較它們,然後將結果與 0 進行比較。如果結果大於 0,則第一個數字大於第二個數字。如果結果小於 0,則第一個數字小於第二個數字。否則,兩個值相同。

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

      // compares the two specified double values
      double d1 = 11.50;
      double d2 = 15.45;
      int retval = Double.compare(d1, d2);
    
      if(retval > 0) {
         System.out.println("d1 is greater than d2");
      } else if(retval < 0) {
        System.out.println("d1 is less than d2");
      } else {
         System.out.println("d1 is equal to d2");
      }
   }
} 

輸出

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

d1 is less than d2

檢查雙精度浮點數是否等於給定雙精度浮點數示例

以下示例演示瞭如何使用 Double compare() 方法來檢查一個值是否等於另一個值。我們有兩個雙精度浮點數,並使用 compare() 方法比較它們,然後將結果與 0 進行比較。如果結果大於 0,則第一個數字大於第二個數字。如果結果小於 0,則第一個數字小於第二個數字。否則,兩個值相同。

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

      // compares the two specified double values
      double d1 = 15.45;
      double d2 = 15.45;
      int retval = Double.compare(d1, d2);
    
      if(retval > 0) {
         System.out.println("d1 is greater than d2");
      } else if(retval < 0) {
        System.out.println("d1 is less than d2");
      } else {
         System.out.println("d1 is equal to d2");
      }
   }
} 

輸出

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

d1 is equal to d2
java_lang_double.htm
廣告