To declare a variable as a Decimal
, first declare it as a Variant
and then convert to Decimal
with CDec
. The type would be Variant/Decimal
in the watch window:
Considering that programming floating point arithmetic is not what one has studied during Maths classes at school, one should always try to avoid common pitfalls by converting to decimal whenever possible.
In the example below, we see that the expression:
0.1 + 0.11 = 0.21
is either True
or False
, depending on whether the collectibles (0.1,0.11) are declared as Double
or as Decimal
:
Public Sub TestMe()
Dim preciseA As Variant: preciseA = CDec(0.1)
Dim preciseB As Variant: preciseB = CDec(0.11)
Dim notPreciseA As Double: notPreciseA = 0.1
Dim notPreciseB As Double: notPreciseB = 0.11
Debug.Print preciseA + preciseB
Debug.Print preciseA + preciseB = 0.21 'True
Debug.Print notPreciseA + notPreciseB
Debug.Print notPreciseA + notPreciseB = 0.21 'False
End Sub