Compare double in VBA precision problem Compare double in VBA precision problem vba vba

Compare double in VBA precision problem


You can't compare floating point values for equality. See this article on "Comparing floating point numbers" for a discussion of how to handle the intrinsic error.

It isn't as simple as comparing to a constant error margin unless you know for sure what the absolute range of the floats is beforehand.


if you are going to do this....

Dim a as double   Dim b as double   a = 0.15   b = 0.01

you need to add the round function in your IF statement like this...

  If Round(a,2) = Round(b,2) Then        //code inside block will now trigger.  End If  

See also here for additional Microsoft reference.


It is never wise to compare doubles on equality.

Some decimal values map to several floating point representations. So one 0.6 is not always equal to the other 0.6.

If we subtract one from the other, we probably get something like 0.00000000051.

We can now define equality as having a difference smaller that a certain error margin.