Tuesday, October 18, 2022

Data type - Double

Data type Double is refer to short for double precision floating point are stored as IEEE 64-bit (8-byte) ranging from:

  • -1.79769313486231E308 to -4.94065645841247E-324 for negative values
  • 4.94065645841247E-324 to 1.79769313486232E308 for positive values

Instead of Dim DbNum as Double we can use Dim DbNum#. The key point here is precision floating point (read more at link below) this can support 15 significant figures with 14 decimal places.

For more example refer below table and code.

Below we try to get area in square meter base on width and length.


VBA Vode:

Option Explicit
Sub Examples_DoubleVariales()
    
    Dim i As Integer
    
    'Double Declaration
    Dim DbWidht As Double, DbLength As Double
    Dim DbSqMtr As Double
    
    'Decimal Declaration
    Dim VarWidht As Variant, VarLength As Variant
    Dim VarSqMtr As Variant
    
    'Integer Declaration
    Dim IntWidht As Integer, IntLength As Integer
    Dim IntSqMtr As Integer
    
    i = 2
    With ActiveSheet
        Do
            'Double
            DbWidht = .Range("B" & i)
            DbLength = .Range("C" & i)
            DbSqMtr = Round(DbWidht * DbLength, 2)
            
            'Decimal
            VarWidht = CDec(.Range("B" & i))
            VarLength = CDec(.Range("C" & i))
            VarSqMtr = CDec(Round(VarWidht * VarLength, 2))
            
            'Integer
            IntWidht = .Range("B" & i)
            IntLength = .Range("C" & i)
            IntSqMtr = Round(IntWidht * IntLength, 2)
            
            'Direct input
            .Range("D" & i) = Round(.Range("B" & i) * _
            .Range("C" & i), 2)
            .Range("E" & i) = DbSqMtr 'Double variables
            .Range("F" & i) = VarSqMtr 'Decimal variables
            .Range("G" & i) = IntSqMtr 'Integer variables
            
            DbWidht = 0: DbLength = 0: DbSqMtr = 0
            VarWidht = 0: VarLength = 0: VarSqMtr = 0
            IntWidht = 0: IntLength = 0: IntSqMtr = 0
            i = i + 1
        Loop Until .Range("A" & i) = ""
    End With

End Sub

Note: The above example we try to compare without variables, Double variables, Decimal variables and Integer variables. Definitely integer is not accurate for this type of data.

Microsoft Reference-Double-data-type
Other Reference-Double-data-type
Other Reference-Floating-point-numbers

Practice makes perfect. Thank You.

macro enabled excel
excel macro
vba coding
vba code

No comments:

Post a Comment