Monday, October 17, 2022

Data type -Decimal

Data type Decimal is stored as 96-bit (12-byte) and range for data without decimal value (0) between +/-79,228,162,514,264,337,593,543,950,335 and with 28 decimal point between +/-7.9228162514264337593543950335 and the smallest, non-zero value is +/-0.0000000000000000000000000001. Beside Decimal we can use Double which is more straight forward but in term accuracy better use Decimal depend on condition.

VBA Vode:

Option Explicit
Sub Examples_Decimal()
    
    'Integer Variable Declaration
    Dim DecVar As Variant
    
    'Assign value to integer variable
    DecVar = CDec(50555555000.1004)

    'Checking what type of data
    Debug.Print TypeName(DecVar) 'Decimal

End Sub

Result: Data type shown as Decimal

VBA Vode:

Option Explicit
Sub Examples_DecimalVsDouble()

    'Variables with Decimal declaration
    Dim DecVarA As Variant, DecVarB As Variant
    
    'Variables with Double declaration
    Dim DblVarA As Double, DblVarB As Double
    
    DecVarA = CDec(0.2): DecVarB = CDec(0.21) 'Decimal
    DblVarA = 0.2: DblVarB = 0.21 'Double
    
    Debug.Print DecVarA + DecVarB = 0.41    'True
    Debug.Print DblVarA + DblVarB = 0.41    'False
    
End Sub

Note: For comparison the result for Variant/Decimal is True but the result for Double is False. Meaning Variant/Decimal is more accurate compare with Double.

Microsoft Reference-Decimal-data-type
Other Reference-Decimal-data-type.htm

Practice makes perfect. Thank You.

excelmacros
macro excel
excel programming
excel vba

No comments:

Post a Comment