Reputation: 686
If small number then it worked, but with larger number then it was wrong. My example code below.
public void TestZZZZZZZZZ()
{
ulong val = ulong.MaxValue; // val = 18446744073709551615
string s = string.Format("{0}", val);
double d = Convert.ToDouble(s);
ulong result = ((ulong)d; // result = 0 <-- WRONG
Assert.AreEqual(val, result);
}
Some test data result:
Is there any my wrong? please help.
Thanks!
Upvotes: 0
Views: 1847
Reputation: 686
My solution here was use decimal to contain value for converting (instead double).
Thanks for all your supporting! Trong.
Upvotes: 0
Reputation:
From Msdn:
Long:Signed 64-bit integer
Double:64-bit floating (15-16 digits Precision)
So result is not same. So if you have just 16 digits your assert is ok. Like M.kazem Akhgary answer.
Upvotes: 2
Reputation: 19149
double Have precision of 16 digits. So test your number for 16 digits.
ulong val = 1234567890123456; // 16 digits
double d = val;
ulong result = (ulong)d;
Console.WriteLine(val == result); // prints true
After this you will loose precision.
ulong val = 12345678901234567; // 17 digits
double d = val;
ulong result = (ulong)d;
Console.WriteLine(val == result); // prints false
Upvotes: 2
Reputation: 1606
That's because long
holds 64 bits of data, and significant precision of double
is only 53 bits.
Upvotes: 7