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?
From the documentation:
...
So if you really need a double, you should use the techique described on the documentation. If you can, change it to a decimal. It' will be slower, but you won't have this type of problem.
Taking a tip from the Java code base, try using
.CompareTo
and test for the zero comparison. This assumes the.CompareTo
function takes in to account floating point equality in an accurate manner. For instance,This predicate should return
true
.floating point number representations are notoriously inaccurate (because of the way floats are stored internally) e.g. x may actually be 0.0999999999 or 0.100000001 and your condition will fail. If you want to determine if floats are equal you need to specific whether they're equal to within a certain tolerance.
i.e.
Exact comparison of floating point values is know to not always work due to the rounding and internal representation issue.
Try imprecise comparison:
The other alternative is to use the decimal data type.
Double
anddouble
is the same thing.double
is just a C# keyword working as alias for the classSystem.Double
The most common thing is to use the aliases! The same forstring
(System.String
),int
(System.Int32
)Also see Built-In Types Table (C# Reference)
It's a standard problem due to how the computer stores floating point values. Search here for "floating point problem" and you'll find tons of information.
In short – a float/double can't store
0.1
precisely. It will always be a little off.You can try using the
decimal
type which stores numbers in decimal notation. Thus0.1
will be representable precisely.You wanted to know the reason:
Float/double are stored as binary fractions, not decimal fractions. To illustrate:
12.34
in decimal notation (what we use) meansThe computer stores floating point numbers in the same way, except it uses base
2
:10.01
meansNow, you probably know that there are some numbers that cannot be represented fully with our decimal notation. For example,
1/3
in decimal notation is0.3333333…
. The same thing happens in binary notation, except that the numbers that cannot be represented precisely are different. Among them is the number1/10
. In binary notation that is0.000110011001100…
.Since the binary notation cannot store it precisely, it is stored in a rounded-off way. Hence your problem.