Open In App

Comparison of double and float primitive types in Java

Improve
Improve
Like Article
Like
Save
Share
Report

Consider the following two codes in Java: 

Java




// This program prints true
class Geeksforgeeks {
  public static void main(String args[]) {
    float f = 5.25f;
    double d = 5.25
    System.out.println(f == d);
  }
}


Output

true

Java




// But this program prints false.
class Geeksforgeeks {
  public static void main(String args[]) {
    float f = 5.1f;
    double d = 5.1;
    System.out.println(f == d);
  }
}


Output

false

Explanation:

The output is true in the first example and false in second. We know that precisions of float and double are different. Size of mantissa for float is 24 and 53 for double. Let us consider the first example of 5.25. Binary representation of integral part is 101 and binary representation of part of the dot is 0.01 (needs only two bits) Let us consider the second example 5.1. The binary representation of an integral part is the same. But binary representation of 0.1 is 1/16 + 1/32 + 1/64 + 1/128 ….. and so on until we reach the end of mantissa or sum becomes more than 0.1. In this case, we reach the end of mantissa and therefore the value of 5.1 becomes different in float and double.

Tabular difference between Double and Float in Java:

  Double Float
1. It’s results are more precised. It’s results are less precised.
2. To store a variable, it takes 8 bytes and total of 64 bit storage. To store a variable, it takes 4 bytes and total of 32 bit storage.
3. It has high range as compared to Float. It has low range when compared with Double.
4. Accuracy of Double is more than Float. Accuracy is less compared to Double.
5.

It uses:

  • 1 bit for sign
  • 11 bits for exponent
  • 52 bits for mantissa

It uses:

  • 1 bit for sign
  • 8 bits for exponent
  • 23 bits for mantissa

Last Updated : 06 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads