double
stores approximate values and thus this case will not be equal:
double d1 = 0.11;
double d2 = 0.44 - 0.33;
Console.WriteLine(d1 == d2);
decimal
stores values more closer to what they are than does a double
so this will be equal:
Console.WriteLine((decimal)d1 == (decimal)d2);
But it is important to note that even decimal
is an approximate value. For example, you could not store the Pi's exact value using a decimal.
It is commonly known that it is not safe to compare double values in .net.
It all depends on the level of precision your calculation needs. For some calculations it is fine to use it, for others it is not.
System.Double
(double
in C#) and System.Single
(float
in C#) are stored as approximate values. For example:
double x = 0.1d;
x will store the closest available double to that value.
Important Distinction
It is very important to note that unlike double
, a decimal
will not store itself by normalizing but it will remember the zeros. For example, try the following code:
decimal dec1 = 1.000000000m;
double dbl11 = 1.000000000;
Console.WriteLine(dec1); // outputs: 1.000000000 (remembers all 9 zeros)
Console.WriteLine(dbl11); // outputs: 1
<==Try Me==>
A decimal
is stored as base 10 in memory but double
and float
are stored in base 2. All of them have the following components: a mantissa, an exponent and a sign. For example:
44.5 could be represented in "decimal floating point" as mantissa 4.45 with an exponent of 1, whereas 4450 would have the same mantissa but an exponent of 3.
You can read more on Floating Points and Decimals if are curious.
Kind of off-topic but Interesting Question
I was talking to someone about decimals and approximations etc. and they brought up this question: Imagine you own a store and you buy 3 items for $1.00. You want to cut even so which customer will have to take the hit and pay the extra penny?