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?
source to share
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?
source to share
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
source to share
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.
source to share
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
source to share