On Thu, 05 Jul 2007 13:09:09 -0700, <ki*******@gmail.comwrote:
int price = 57;
double taxedPrice1 = price + (price * .18);
double taxedPrice2 = price * 1.18;
//...
Why does taxedPrice1 == "67.26" while taxedPrice2 ==
"67.259999999999991" ?
In addition to what Joe wrote, see Jon Skeet's discussion on floating
point:
http://www.pobox.com/~skeet/csharp/floatingpoint.html
The basic issue is that the decimal values being used can't be represented
exactly. In fact, the variable taxedPrice1 isn't really stored as
67.26...it just happens that it differs just enough from the value stored
in taxedPrice2 that the debugger displays the value rounded.
If you look at the binary values in the debugger, you'll find they differ
by just a single bit, the least-significant one. That difference is
caused by the subtle difference in precision caused by using the constant
0.18 in one calculation and the constant 1.18 in the other. But neither
result is actually represented internally as exactly 67.26. You should
use the decimal type if that's what you want.
Pete