Floating point math is inherently inaccurate. If you want accuracy, you MUST use
decimal
types. Yes, it's a hassle to convert before doing the math, but it's necessary if you want guaranteed precision.
BTW, a
float
(or
double
) will maintain it's value until you perform a math operation on it. At that point, it's value is NOT guaranteed to be completely accurate, and comparisons are not guaranteed to have the results you expect.
Using
decimal
is the one true path.
Try it this way:
MyResult = Convert.ToSingle(Convert.ToDecimal(MySingle1) - Convert.ToDecimal(MySingle2))
And see if the value isn't precisely what you expect.
To avoid the casting, simply start using decimal for all of your
Single
or
Double
variables.
ALTERNATIVE - use the
Math.Round
method to round to a certain precision, but that's fake math. I prefer the precision of the
decimal
type (even though it takes a little longer to do math ops on them).