Java 中的 Float 比較


要比較 Java 中的 Float,請使用以下方法 −

方法 1 − Java 中的 compareTo(newFloat) 方法

java.lang.Float.compareTo() 方法比較兩個 Float 物件。此方法如果 new float 值在此 Float 中以數值相等,則返回 0;如果此 Float 在以數值上小於 new float,則返回小於 0 的值;如果此 Float 在以數值上大於 new float,則返回大於 0 的值。

示例如下 −

示例

 即時演示

import java.lang.*;
public class Demo {
   public static void main(String args[]) {
      Float f1 = new Float("25.2");
      Float f2 = new Float("25.20");
      int res = f1.compareTo(f2);
      if(res > 0) {
         System.out.println("f1 is greater than f2");
      }
      else if(res < 0) {
         System.out.println("f1 is less than f2");
      }
      else {
         System.out.println("f1 is equal to f2");
      }
   }
}

輸出

f1 is equal to f2

方法 2 − Java 中的 compare(f1, f2) 方法

java.lang.Float.compare() 方法以數值比較兩個 float 值物件。如果 f1 在以數值上等於 f2,則此方法返回 0;如果 f1 在以數值上小於 f2,則返回小於 0 的值;如果 f1 在以數值上大於 f2,則返回大於 0 的值。

我們來看一個示例 −

示例

 即時演示

import java.lang.*;
public class Demo {
   public static void main(String args[]) {
      float f1 = 29.29f;
      float f2 = 55.55f;
      int res = Float.compare(f1, f2);
      if(res > 0) {
         System.out.println("f1 is greater than f2");
      }
      else if(res < 0) {
         System.out.println("f1 is less than f2");
      }
      else {
         System.out.println("f1 is equal to f2");
      }
   }
}

輸出

f1 is less than f2

更新於: 2020-6-26

檢視次數 203

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告