Why body of if()
in 1st code Executes While the body of if()
in 2nd code Doesn't Executes
Working
double num1 = 0.2;
double num2 = 0.2;
double num3 = num1 + num2;
if (num3 == 0.4)
{
MessageBox.Show("1st");
}
Not Working
double num1 = 0.1;
double num2 = 0.2;
double num3 = num1 + num2;
if (num3 == 0.3)
{
MessageBox.Show("2nd");
}
Machine uses binary language When it convert number into binary , convert back into decimal The value get changed ,due to some number can't be converted Completely in binary
When you convert
0.1 into base 2 (binary)
you get a repeating pattern after the decimal point,Like 1/3 in base 10 ;
1/3=0.333333333333333333333333333333333..........
& never get Exact valueTherefor you can't Get every number's exact Value using normal floating point methods.
0.1 Pattern In Binary...
Source: Why 0.1 Does Not Exist In Floating-Point
0.1 Conversion
0.1 is one-tenth, or 1/10. To show it in binary
You can See100
is repeating after intervals As Giving output as1001
as Shown In DiagramSource: Why 0.1 Does Not Exist In Floating-Point
Source:Is floating point math broken?
Source:Why 0.1 Does Not Exist In Floating-Point
Further Guide About Float Point
Guide By Oricle
Examine Number
IEEE 754 double-precision binary floating-point format