float totalAmount = 0;
.
.
.//totalAmount assigned value 1.05 correctly
.
totalAmount += float.Parse(dataRow["Amt"].ToString()); //where dataRow["Amt"] has value 4.93
The answer I get for totalAmount is 5.97999954 instead of 5.98
Why is this happening?
You state that
totalAmountis 1.05, before the accumulation. That would give expected results of:You are getting 5.97999954, which is basically the answer as best represented by IEEE floating point, which is a binary format that cannot exactly express every decimal number. For instance, the rather common 0.110 has an infinite binary floating point representation
.0001100110011...2.And a Wikipedia link, for good measure: http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems 😉