Comparing Floating-Point Numbers - Java Language Basics

Java examples for Language Basics:float

Solution 1

Use the Float object's compareTo() method to compare float values.

Float float1 = new Float("9.6175"); 
Float float2 = new Float("7.38126"); 
Float float3 = new Float("2347.373"); 

System.out.println(float1.compareTo(float3));  
System.out.println(float2.compareTo(float3));  
System.out.println(float1.compareTo(float1));  
System.out.println(float3.compareTo(float2));  

The result of calling the compareTo() method is an integer value.

  • A negative result indicates that the first float is less than the float that it is being compared against.
  • A zero indicates that the two float values are equal.
  • A positive result indicates that the first float is greater than the float that it is being compared against.

Solution 2

Use the Float class compare() method to perform the comparison.

System.out.println(Float.compare(float1, float3));
System.out.println(Float.compare(float2, float3));
System.out.println(Float.compare(float1, float1));
System.out.println(Float.compare(float3, float2));

Demo Code

public class Main {
    //ww  w .j  a v  a  2s  . c o  m
    public static void main(String[] args){

        Float float1 = new Float("9.6175"); 
        Float float2 = new Float("7.38126"); 
        Float float3 = new Float("2347.373"); 
        
        System.out.println("-- Using compareTo --");
        System.out.println(float1.compareTo(float3));
        System.out.println(float2.compareTo(float3));
        System.out.println(float1.compareTo(float1));
        System.out.println(float3.compareTo(float2));
       
        
        System.out.println("-- Using compare --");
        System.out.println(Float.compare(float1, float3));
        System.out.println(Float.compare(float2, float3));
        System.out.println(Float.compare(float1, float1));
        System.out.println(Float.compare(float3, float2));
    }
}

Result


Related Tutorials