C# The “double” trouble
This is a very simple question with a not so simple answer…
Forget for a second about .NET.
If someone asks you how much is 1.000025 – 0.000025 your answer will probably be “1″ and correct. An easy question, right ?
Now, let’s go back to .NET and check if our calculations are correct.
static void Main(string[] args)
{
double d1 = 1.000025;
double d2 = 0.000025;
Console.WriteLine((d1 - d2) == 1);
}
If you think the result will be “true”… well, it’s not.
Let’s see another example :
static void Main(string[] args)
{
double d1 = 1.000025;
double d2 = 0.000025;
// Will result 1
Console.WriteLine(d1 - d2);
// Will result 0.99999999999999989
Console.WriteLine((d1 - d2).ToString ("R"));
}
For those who might not know, the meaning of ToString(“R”) is Round-trip.
This format is supported only for the Single and Double types. The round-trip specifier guarantees that a numeric value converted to a string will be parsed back into the same numeric value. When a numeric value is formatted using this specifier, it is first tested using the general format, with 15 spaces of precision for a Double and 7 spaces of precision for a Single. If the value is successfully parsed back to the same numeric value, it is formatted using the general format specifier. However, if the value is not successfully parsed back to the same numeric value, then the value is formatted using 17 digits of precision for a Double and 9 digits of precision for a Single.
So, what happened here ? Is it a bug ?
The answer is – NO, IT’S NOT A BUG ( and it’s not happening only on my computer ).
The thing is, that the above is about how .NET rounding a floating point number.
I won’t explain here the math ( there is already a great article explaining it ), and i won’t say don’t use floating point types.
You just need to know that when you are using it – be carefull, especialy in equations and formatting, otherwise your calculations will be wrong and your result not accurate.

