G
Guest
Hi,
this is not the usual why-can't-I-represent-0.1-in-double post.
I don't understand why we loose information when converting from double to
decimal.
Consider the following code. d1 and d2 are clearly different.
When converting to decimal, I expect dec1 and dec2 to be different too.
decimal tries to be smart and rounds 0.082000000000000017 to 0.082
although it is possible to represent 0.082000000000000003 exactly in decimal.
Is this documented somewhere?
double d1 = 0.082000000000000003;
double d2 = 0.082000000000000017;
long l = 82000000000000017;
System.Diagnostics.Trace.WriteLine(d1.ToString("G17")); //
0.082000000000000003
System.Diagnostics.Trace.WriteLine(d2.ToString("G17")); //
0.082000000000000017
decimal dec1 = (decimal)(d1);
decimal dec2 = (decimal)(d2);
decimal dec3 = (decimal)(l) / 1e18m;
decimal dec4 = decimal.Parse(d2.ToString("G17"));
System.Diagnostics.Trace.WriteLine(dec1.ToString("G17")); // 0.082
System.Diagnostics.Trace.WriteLine(dec2.ToString("G17")); // 0.082
System.Diagnostics.Trace.WriteLine(dec3.ToString("G17")); //
0.082000000000000017
System.Diagnostics.Trace.WriteLine(dec4.ToString("G17")); //
0.082000000000000017
TIA
Henrik
this is not the usual why-can't-I-represent-0.1-in-double post.
I don't understand why we loose information when converting from double to
decimal.
Consider the following code. d1 and d2 are clearly different.
When converting to decimal, I expect dec1 and dec2 to be different too.
decimal tries to be smart and rounds 0.082000000000000017 to 0.082
although it is possible to represent 0.082000000000000003 exactly in decimal.
Is this documented somewhere?
double d1 = 0.082000000000000003;
double d2 = 0.082000000000000017;
long l = 82000000000000017;
System.Diagnostics.Trace.WriteLine(d1.ToString("G17")); //
0.082000000000000003
System.Diagnostics.Trace.WriteLine(d2.ToString("G17")); //
0.082000000000000017
decimal dec1 = (decimal)(d1);
decimal dec2 = (decimal)(d2);
decimal dec3 = (decimal)(l) / 1e18m;
decimal dec4 = decimal.Parse(d2.ToString("G17"));
System.Diagnostics.Trace.WriteLine(dec1.ToString("G17")); // 0.082
System.Diagnostics.Trace.WriteLine(dec2.ToString("G17")); // 0.082
System.Diagnostics.Trace.WriteLine(dec3.ToString("G17")); //
0.082000000000000017
System.Diagnostics.Trace.WriteLine(dec4.ToString("G17")); //
0.082000000000000017
TIA
Henrik