Compare two float objects

static int compare(float f1, float f2)
Compares the two specified float values.
int compareTo(Float anotherFloat)
Compares two Float objects numerically.
boolean equals(Object obj)
Compares this object against the specified object.

static int compare(float f1, float f2) compares the two specified float values. It returns:

ValueMeaning
0if f1 is numerically equal to f2;
less than 0if f1 is numerically less than f2;
greater than 0if f1 is numerically greater than f2.

public class Main {
  public static void main(String[] args) {
    Float floatObject1 = new Float("10.0001");
    Float floatObject2 = new Float("10.0002");
    
    System.out.println(Float.compare(floatObject1,floatObject2));
    
  }
}

The output:


-1

The following code create a NaN(Not a Number) float value by dividing 0, and then compare it with another float value:


public class Main {
  public static void main(String[] args) {
    Float floatObject1 = new Float("10.0001");
    
    Float floatObject2 = Float.valueOf((float)0.0/(float)(0.0));
    System.out.println(floatObject2);
    
    System.out.println(Float.compare(floatObject1,floatObject2));
    
  }
}

The output:


NaN
-1

int compareTo(Float anotherFloat) compares two Float objects numerically.

Float.NaN is considered to be equal to itself and greater than all other float values including Float.POSITIVE_INFINITY. 0.0f is considered by this method to be greater than -0.0f.

It returns:

0
if anotherFloat is numerically equal to this Float;
less than 0
if this Float is numerically less than anotherFloat;
greater than 0
if this Float is numerically greater than anotherFloat.

public class Main {
  public static void main(String[] args) {
    Float floatObject1 = new Float("10.0001");
    
    Float floatObject2 = Float.valueOf((float)0.0/(float)(0.0));
    System.out.println(floatObject2);
    
    System.out.println(floatObject1.compareTo(floatObject2));
    
  }
}

The output:


NaN
-1
Home 
  Java Book 
    Essential Classes  

Float:
  1. Float class
  2. MAX/MIN_VALUE Find out the Maximum value and Minimum value a float type can have
  3. Create a Float object
  4. Convert Float to byte, double, float, int, long and short
  5. Compare two float objects
  6. Infinite and Not A Number
  7. Convert float value to Hex String value
  8. Convert float value to String value
  9. Convert string value to float value
  10. Bit oriented calculation for float