Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Comparison of double and float primitive types in Java
If we compare a float and a double value with .5 or .0 or .1235 (ending with 5 or 0), then == operator returns true, otherwise it will return false. See the below example.
Example
public class Tester {
public static void main(String[] args) {
double d1 = 2.5;
float f1 = 2.5f;
System.out.println(d1 == f1);
double d2 = 2.4;
float f2 = 2.4f;
double margin = 0.0000001;
System.out.println(compareNumbers(d2, f2, margin));
}
private static boolean compareNumbers(double d, float f, double margin) {
if(Math.abs(d - f) < margin) {
return true;
}
return false;
}
}
Output
true true
Advertisements
