Menu

### Decimal Values Comparison (floats & double)

As we all know that float and double are data type

Float

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

Double

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”)
}
Else
{
System.out.println (“false”);
}
Output will Be :
false

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
{
System.out.println(“true”);
}
else
{
System.out.println(“false”);
}
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
0.2*2=0.4——->0
0.4*2=0.8——->0
0.8*2=1.6——->1
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:-
10.25=1010.01

After the decimal value ,we convert it as:
.25*2=0.50——->0
0.50*2=1.00——>1…..
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).

11 Comments