[RESOLVED] access vba: problem with condition in if statement
Hi
I have a string array called tokens that has been previously filled. I convert some of the tokens to doubles and add them together, but sometimes it seems to evaluate incorrectly. I have a case where it should evaluate to true, but is evaluating to false for some reason I can't understand. Any ideas on what I'm missing or what I can do to fix this? Last time I checked 2.73+17.51=20.24 was a true statement... Is VBA just retarded!?
VB Code:
'try the new algorithm to fill the variables
If ((CDbl(tokens(3)) + CDbl(tokens(5))) = CDbl(tokens(1))) Then
'Why isn't this evaluating to true on record 8 for 9730 - 7267
'tokens(3) = 2.73
'tokens(5) = 17.51
'tokens(1) = 20.24
paidToAgency = tokens(1)
paidToYou = 0
Else
'Now try to figure it out based on tabs...
If (CInt(Mid(tokens(0), 3)) > CInt(Mid(tokens(2), 3))) Then
paidToYou = tokens(1)
paidToAgency = 0
Else
paidToAgency = tokens(1)
paidToYou = 0
tableName = "tblBadData"
End If
End If
Here is a copy of my immediate window during execution:
Code:
?(CDbl(tokens(3)) + CDbl(tokens(5))) = CDbl(tokens(1))
False
?tokens(3)
2.73
?tokens(5)
17.51
?tokens(1)
20.24
Thanks,
Ranthalion
Re: access vba: problem with condition in if statement
Try
?format$(Cdbl(tokens(3)) + Cdbl(tokens(5)),"00.00000000000")
?format$(Cdbl(tokens(1)),"00.00000000000")
Doubles are notorious for their rounding problems maybe your code trippes of this.
Re: access vba: problem with condition in if statement
Almost ANY decimal-to-binary-to-decimal conversion using complex numbers (numbers with decimals) will have rounding errors. (You can choose a few that won't, but most will, which is why BCD arithmetic was invented.) Never test for equality, test for the difference being smaller than what you care about - < 0.01 in this case.
Re: access vba: problem with condition in if statement
Thanks. I was aware of accuracy issues with doubles, but I figured that since it was given a decimal with only 2 decimal points that it wouldn't be a problem. :-) Guess I was wrong... First time I've ever run into an issue with doubles actually messing anything up, but it was a good lesson learned. Once again, thanks for the help.
Re: [RESOLVED] access vba: problem with condition in if statement
A way to solve your problem is to use currency instead of doubles, if you just need two decimals.