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
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
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:
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).