I've a double
variable called x
.
In the code, x
gets assigned a value of 0.1
and I check it in an 'if' statement comparing x
and 0.1
if (x==0.1)
{
----
}
Unfortunately it does not enter the if
statement
Should I use
Double
ordouble
?What's the reason behind this? Can you suggest a solution for this?
double
andDouble
are the same (double
is an alias forDouble
) and can be used interchangeably.The problem with comparing a double with another value is that doubles are approximate values, not exact values. So when you set
x
to0.1
it may in reality be stored as0.100000001
or something like that.Instead of checking for equality, you should check that the difference is less than a defined minimum difference (tolerance). Something like:
Comparing floating point number can't always be done precisely because of rounding. To compare
the computer really compares
Result of sybtraction can not always be represeted precisely because of how floating point number are represented on the machine. Therefore you get some nonzero value and the condition evaluates to
false
.To overcome this compare
Double and double are identical.
For the reason, see http://www.yoda.arachsys.com/csharp/floatingpoint.html . In short: a double is not an exact type and a minute difference between "x" and "0.1" will throw it off.