Search code examples
c#stringdoubletostringstring-concatenation

Double type strange behavior while concatenating with String or Converting to String


I have logging functionality in project which compares objects value and displays differences but i have a scenarion i have latitude and longitude values in double data type but when i concatenate it with string or convert it to string i am getting strange behaviour as it is showing the same value in both variables which is totally not understandable how it is happening.

Here is the code:

double value1 = -6.2845230102539063;
double value2 = -6.2845230102539098;
        if (!object.Equals(value1, value2))
        {
            var result = value2 + " to " + value1;
            Console.WriteLine(result);
        }

        Console.ReadLine();

Expected Output :

-6.2845230102539098 to -6.2845230102539063

Actual Output :

-6.28452301025391 to -6.28452301025391

Here is DEMO FIDDLE:

https://dotnetfiddle.net/0XM3Da

What is happening here?


Solution

  • From MSDN: http://msdn.microsoft.com/en-us/library/678hzkk9.aspx

    Double has a precision of 15-16 digits. You've exceeded that limit. You should use Decimal instead. See here for details: Can C# store more precise data than doubles?