
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 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; System.out.println(d2 == f2); } }
Output
true false
The reason behind this logic is the approximation of float and decimal. Float data type is a single-precision 32-bit IEEE 754 floating point and double data type is a double-precision 64-bit IEEE 754 floating point. A number ending with 5 or 0 can be represented exactly in both double and float.
In case of other numbers, it is similar to comparing 0.3333 to 0.33333333 where precision of later is high.
Correct way of comparing double and float
In order to compare double and float, check the difference of two to be greater than or less than a particular margin. See the example below.
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
- Related Questions & Answers
- Comparison of double and float primitive types in C#
- Comparison of Float in Java
- Java Program to convert Java Float to Numeric Primitive Data Types
- Java Program to convert Double to numeric primitive data types
- Round float and double numbers in Java
- Java primitive data types
- Float and Double in C
- Convert double primitive type to a Double object in Java
- Difference Between Float and Double
- What is the most effective way for float and double comparison in C/C++?
- Default value of primitive data types in Java
- What are Primitive and Non-Primitive Data Types in JavaScript?
- Get the absolute value of float, int, double and long in Java
- Difference between float and double in Arduino
- What are primitive data types in Java?
Advertisements