There is no exact double
representation for a lot of numbers.
The double
number the nearest from 1.9999999999999999
is 2
, so the compiler rounds it up.
Try to print it before using your Math.Floor
function !
However, the nearest from 1.9999999999999998
is still 1.something
, so Floor
gives out 1
.
Again, it would be enough to print the number before the function Floor
to see that they were actually not anymore the one entered in the code.
EDIT : To print out the number with most precision :
double a1 = 1.9999999999999998;
Console.WriteLine(a1.ToString("G17"));
// output : 1.9999999999999998
double a2 = 1.9999999999999999;
Console.WriteLine(a2.ToString("G17"));
// output : 2
Since double precision is not always precise to 17 significative digits (including the first one before the decimal point), default ToString()
will round it up to 16 significant digits, thus, in this case, rounding it up to 2
as well, but only at runtime, not at compile time.