Random double type behavior when concatenating with String or converting to string

I have a logging function in a project that compares the values ​​of objects and displays the differences, but I have a script. I have latitude and longitude values ​​in a double datatype, but when I concatenate it to a string or convert it to a string, I get weird behavior as it shows the same value in both variables, which is completely incomprehensible how this happens.

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 Result:

-6.2845230102539098 - -6.2845230102539063

Actual output:

-6.28452301025391 -6.28452301025391

Here is the DEMO FIDDLE :

https://dotnetfiddle.net/0XM3Da

What's going on here?

+3


source to share


5 answers


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



The double has a precision of 15-16 digits. You have exceeded this limit. You should use Decimal instead. See here for more details: Can C # Store More Accurate Data Than Paired Data?

+3


source


This is described in @LukeH's answer for "Formatting doubles for output in C #":

The problem is that .NET will always round double

to 15 significant decimal digits before applying formatting, regardless of the precision requested by your format and regardless of the exact decimal value of the binary number.

Using the DoubleConverter class associated with this answer we get

var x = -6.2845230102539063;
var y = -6.2845230102539098;

Console.WriteLine(x == y);
Console.WriteLine(x);
Console.WriteLine(y);
Console.WriteLine(DoubleConverter.ToExactString(x));
Console.WriteLine(DoubleConverter.ToExactString(y));

      

which prints



False
-6.28452301025391
-6.28452301025391
-6.28452301025390625
-6.284523010253909802713678800500929355621337890625

      

Or you can use the G17 format specification

Console.WriteLine(x.ToString("G17"));
Console.WriteLine(y.ToString("G17"));

      

which will give you

-6.2845230102539063
-6.2845230102539098

      

+2


source


From: http://msdn.microsoft.com/en-us/library/kfsatb94(v=vs.110).aspx

'By default, the return value contains only 15 digits of precision, although no more than 17 digits are internally supported.'

So he knows they are not the same size, but he does not display them that way.

0


source


The double value has up to 15 decimal digits of precision, you can refer to the detailed explanation http://msdn.microsoft.com/zh-cn/library/system.double(v=vs.110).aspx

0


source


Have you tried decimal data type. This gives you an accurate representation of the numbers ... for the banking and stock markets, I suppose. And you can shrink the mantissa to a certain length (18 maybe).

0


source







All Articles