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.