Why can't I get simple multipliation answer

  • Thread starter Thread starter Amil
  • Start date Start date
A

Amil

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
 
Amil said:
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

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.
 
.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.

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
 
Back
Top