Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
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
Advertisements