I’m using Calc BASIC macros for various financial processing. When I enter a transaction amount, like “10.93”, I load that value into a Single variable, and according to my Watch as I step through the code, the value is actually 10.93. But then when I store that value into a cell like so:
shtJournal.getCellByPosition(6,jrnlRow).setValue(nCredit)
the value that shows up in the cell is actually 10.9300003051758. If I change the code to this:
shtJournal.getCellByPosition(6,jrnlRow).setValue(Int(nCredit*100+0.5)/100)
then it seems to store the value 10.93. This doesn’t make any sense to me. I understand that doing math on Single numbers results in little differences out 8 or 10 decimals, but if I just pull the value 10.93 out of a cell, and later do a setValue of it somewhere else, shouldn’t the value in the cell be the same value? Or looking at things the other way around, the second code snippet above seems to produce the desired result, but it is doing a series of calculations on a Single number; when it gets to the point of calculating 1093/100 (before the setValue), why doesn’t it produce 10.9300003051758 instead of 10.93? I would think it was more susceptible to rounding problems because it is the result of a mathematical expression, rather than just loading a value and saving it out!
In another place I used this code:
Val(Format(nAmount, "0.##"))
and that also seems to work pretty well, turning the number into a string that has at most 2 decimal places and then getting the value of that string. But the bottom line is that I don’t really understand why things happen this way, and when I see problems, I figure out code which seems to “solve the problem”, but if I understood things better, maybe I could write the code in the first place that would avoid the problems.
So any suggestions or advice or pointers to pages to read?