Re: Losing precision when converting to double

Vince P <[email protected]> Mon, 30 Oct 2006 08:30:12 -0600
Newsgroups gmane.comp.windows.devel.dotnet.cx
Message-ID <003401c6fc2f$e95397f0$bbfac7d0$@net>
Did you read the Documentation for the Decimal structure?

Quote:

System.Decimal

Conversions from Decimal to other types are narrowing conversions that round
the Decimal value to the nearest integer value toward zero. If the result of
the conversion is not representable in the destination type, an
OverflowException is thrown.

This type provides methods that convert Decimal values to and from Single
and Double. Conversions from Decimal to Single or Double are narrowing
conversions that might lose precision but not information about the
magnitude of the converted value. The conversion will not throw an
exception.


-----Original Message-----
From: Discussion relating to the specifics of the C# and Managed C++
languages [mailto:[email protected]] On Behalf Of Mikael
Bergforsen
Sent: Monday, October 30, 2006 6:47 AM
To: [email protected]
Subject: [DOTNET-CX] Losing precision when converting to double

Whenever the result of an operation is a double I loose precision; here
are some examples:

double a = 1111.111111111;  //a = 1111.1111111109999 OK

converting from decimal
double a = Convert.ToDouble(1111.111111111M); //a = 1111.111083984375 NOT
OK

result of addition
double a = 1111.111111111;
double b = 1111.111111111;
double c = a + b; //c = 2222.22216796875 NOT OK
double c = 2222.222222222; // c = 2222.2222222219998 OK

Any idea why this happens?

===================================
This list is hosted by DevelopMentorR  http://www.develop.com

View archives and manage your subscription(s) at http://discuss.develop.com

===================================
This list is hosted by DevelopMentorĀ®  http://www.develop.com

View archives and manage your subscription(s) at http://discuss.develop.com