none
Unexpected result RRS feed

  • Question

  • I need to understand why VB thinks that the result of 4355.72 + 1340.22

    IS NOT EQUAL TO 5695.94

     

    Example:

    Sub Test()
        If (4355.72 + 1340.22) <> 5695.94 Then
            MsgBox (4355.72 + 1340.22) & " is not equal to " & 5695.94
        End If
    End Sub

    The MsgBox shows that 5695.94 is not equal to 5695.94, but I have no idea why. 


    Another funny example:

    Sub AnotherText()

    Dim C As Currency
    Dim V As Double

        Do
            C = C + 0.01
            V = V + 0.01
            If C <> V Then
                MsgBox "C= " & C & " but V= " & V
                Debug.Print "C= " & C, "but V= " & V
                End
            End If
        Loop
    End Sub
     

    This code will stop showing that C= 216936.97 but V= 216936.97005

    Why 0.00005 more?

    HELP!!! I have searched but not found an answer. The same occurs in VB6 and VBA.

    Thks,

    Roberto Lisbôa Villa Real

     

     

    Wednesday, June 22, 2011 7:05 AM

All replies

  • I've just found this answer:

     

    It is caused by the binary representation of the number. A double and a float have to assign some bits of the bytes it is using for precision. (by Philip_Stuyck__)

     

    But I'd like to find further explanation about this binary representation problem.

    Thanks!!

    Roberto Lisbôa Villa Real

    Wednesday, June 22, 2011 7:15 AM