Edit
(to answer the "Why 310 == 3.1 * 100" part )
This is only "by chance" that 3.1 * 100 == 310
.
It just happens that the particular way of how floating points arithmetics work,
the result of 3.1 * 100 gives 310.0000...
. This numbers exactly matches the result you get if you convert 310 to a double.
The comparison will happily work in this particular case.
You can have a look at it with the DoubleConverter.ToExactString() function from Jon Skeet
Console.WriteLine(DoubleConverter.ToExactString(3.1 * 100));
Console.WriteLine(DoubleConverter.ToExactString(4.1 * 100));
// output :
// 310
// 409.99999999999994315658113919198513031005859375
(Previous)
In this particular case, the expression 4.1 * 100D
is a double
multiplied by a double
.
The same error would be caused by 4.1 * 100
(double
times int
-> the int
gets implicitly cast as double
)
Since no type is specified for your variable, the compiler chooses to interpret the result as double
. A rounding error due to floating-point arithmetic occurs in this particular case (4.1 has no exact representation as double
)
If the variable is defined as decimal
, the result is a decimal
, and no rounding error occurs. Note that you cannot just change the var
to decimal
in the code you provided, you have to change your variables as well :
In this case, the multiplication will then give the exact value as decimal in both cases.
More on the floating-point errors here : Is floating point math broken?
decimal a1 = 4.1 * 100D; // compilation error : no implicit cast from double to decimal
decimal a1 = 4.1M * 100; // valid, and the multiplication will be performed exactly.