Groups | Blog | Home
all groups > dotnet framework > february 2006 >

dotnet framework : Why can't I get simple multipliation answer


Amil
2/25/2006 6:24:57 PM
I want to multiple two decimal numbers and get the normal result...instead,
I get a very large decimal result. Any idea how I can correct this problem?

double d1 = 5.21;
double d2 = 8.8;
double d = d1 * d2;
// d is now 45.848000000000006 in debugger or WriteLine

Thanks for the help.

Amil

Bill Burwell
2/25/2006 8:56:01 PM
[quoted text, click to view]

Floating point numbers, like d1, d2, & d, can not store the exact equivalent
of most decimal numbers (think of it as a conversion problem). So d1 & d2
have very close approximations of the 5.21 & 8.8 values. And d has the
product of those two approximate floating point numbers. My calculator says
the product should be 45.848 - using only decimals not floating point
numbers. This is a bulls-eye.

This problem exists with floating point numbers on all computers and all
compiler languages.

You can use formatting to lose the confusing ...0006 if you want.

..Net offers a Decimal data type that avoids conversions between decimal and
floating point. But Decimal is (a little) slower than floating point.
Warning, you need to define them as
\\\
decimal d1 = 5.21m;
decimal d2 = 8.8m;
///
with the trailing m. With out the "m" the compile will convert the numbers
to floating point and then convert them again to decimal. Those conversions
are what you need to avoid.

Jon Skeet [C# MVP]
2/26/2006 12:00:00 AM
[quoted text, click to view]

See http://www.pobox.com/~skeet/csharp/floatingpoint.html

--
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
Jon Skeet [C# MVP]
2/26/2006 12:00:00 AM
[quoted text, click to view]

<snip>

[quoted text, click to view]

Slight correction - without the m, the code won't compile:

error CS0664: Literal of type double cannot be implicitly
converted to type 'decimal'; use an 'M' suffix to create a literal of
this type

--
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
AddThis Social Bookmark Button