115
4-5. Comparing Floating-Point Numbers
Problem
You need to compare two or more floating-point values in an application.
Solution 1
Use the Float object’s compareTo() method to compare one float against another. The
following example shows the compareTo() method in action.
public static void compareFloat(){
Float float1 = Float.valueOf ("9.675");
Float float2 = Float.valueOf ("7.3826");
Float float3 = Float.valueOf ("23467.373");
System.out.println(float1.compareTo(float3)); // Result: -1
System.out.println(float2.compareTo(float3)); // Result: -1
System.out.println(float1.compareTo(float1)); // Result: 0
System.out.println(float3.compareTo(float2)); // Result: 1
}
The main class is:
public static void main(String[] args){
compareFloat();
}
The result of calling the compareTo() method is an integer value.
A negative result
indicates that the first float is less than the float being compared against. A zero indicates
that the two float values are equal. Lastly, a positive result indicates
that the first float is
greater than the float being compared against.
Chapter 4 Numbers aNd dates