Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Decimal Values Comparison (floats & double)

As we all know that Float and Double are data type


It takes 4 bytes in java. It can store only 6 digit after the Decimal point.


By default any Decimal Values treated as double value. It takes 8 bytes of memory and it can store 15 values after point.

If I declare the variable as – float f=10.22;

It means I am assigning double value to float which is not possible directly. We have to write ‘f’ after 10.22 like f=10.22f. Because by default any value treated as double.

So, during comparison what happens, let’s discuss-

If I takes a variable as-
float num=10.3f ; // now 10.3 is float value // If I compare it with double value
if (num==10.3)
System.out.println (“true”)
System.out.println (“false”);
Output will Be :

Again I am comparing the values

float num=10.25f ; // now 10.3 is float value // if I compare it with double value
if(num==10.25) // comparing with double
Output will be :
– True

Why the output is varying

When 10.3 is converted to binary format. This is written as 1010.010011 After the decimal values we convert it as follows:

.3*2=0.6——-> 0
0.6*2= 1.2——->1…….

Here as 6 appeared this procedure will again repeat for the n times.

In float it takes only 6 digits after decimal value & In case of double it takes 15 digits after decimal value.
So, the difference occurs during the comparison. And the result becomes “false”.

If I takes 2nd scenario of 10.25f and convert it to binary:-

After the decimal value ,we convert it as:
Now as 0 has appeared , convert it to to binary.

In case of float it will store 2 digits easily after decimal value.

In case of double it will also stores 2 digits after decimal value because 10.25 has only 2 digits after decimal value.

So, during comparison both are same and results become “true”
Next Topic discussion will be on decimal “.” (Decimal Dot).

This post first appeared on Autoboxing In Java | My CMS, please read the originial post: here

Share the post

Decimal Values Comparison (floats & double)


Subscribe to Autoboxing In Java | My Cms

Get updates delivered right to your inbox!

Thank you for your subscription