Comparison of Float in Java


To compare Float in Java, use the following methods −

Method 1 − compareTo(newFloat) method in Java

The java.lang.Float.compareTo() method compares two Float objects. This method returns the value 0 if the new float value is numerically equal to this Float; a value less than 0 if this Float is numerically less than new float; and a value greater than 0 if this Float is numerically greater than new float.

Here is an example −

Example

 Live Demo

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");
      }
   }
}

Output

f1 is equal to f2

Method 2 − compare(f1, f2) method in Java

The java.lang.Float.compare() method compares two float values objects numerically. This method returns the value 0 if f1 is numerically equal to f2; a value less than 0 if f1 is numerically less than f2; and a value greater than 0 if f1 is numerically greater than f2.

Let us see an example −

Example

 Live Demo

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");
      }
   }
}

Output

f1 is less than f2

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 26-Jun-2020

147 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements