Java - Float compare() 方法



描述

Java Float compare() 方法比較兩個指定的浮點值。返回的整數值的符號與呼叫以下程式碼返回的整數值的符號相同:

new Float(f1).compareTo(new Float(f2))

宣告

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

public static int compare(float f1, float f2)

引數

  • f1 − 這是第一個要比較的浮點數

  • f2 − 這是第二個要比較的浮點數。

返回值

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

異常

使用 compare() 方法比較浮點值示例

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

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

      // compares the two specified float values
      float f1 = 15.45f;
      float f2 = 11.50f;
      int retval = Float.compare(f1, f2);
    
      if(retval > 0) {
         System.out.println("f1 is greater than f2");
      } else if(retval < 0) {
        System.out.println("f1 is less than f2");
      } else {
         System.out.println("f1 is equal to f2");
      }
   }
} 

輸出

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

f1 is greater than f2

使用 compare() 方法比較不同的浮點值示例

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

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

      // compares the two specified float values
      float f1 = 11.50f;
      float f2 = 15.45f;
      int retval = Float.compare(f1, f2);
    
      if(retval > 0) {
         System.out.println("f1 is greater than f2");
      } else if(retval < 0) {
        System.out.println("f1 is less than f2");
      } else {
         System.out.println("f1 is equal to f2");
      }
   }
} 

輸出

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

f1 is less than f2

使用 compare() 方法比較相同的浮點值示例

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

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

      // compares the two specified float values
      float f1 = 15.45f;
      float f2 = 15.45f;
      int retval = Float.compare(f1, f2);
    
      if(retval > 0) {
         System.out.println("f1 is greater than f2");
      } else if(retval < 0) {
        System.out.println("f1 is less than f2");
      } else {
         System.out.println("f1 is equal to f2");
      }
   }
} 

輸出

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

f1 is equal to f2
java_lang_float.htm
廣告
© . All rights reserved.