Monday, August 8, 2022

[FIXED] Why do I get a decimal error when I substract two numbers with Excel VBA?

Issue

I have made a simplified example that shows my issue. When substracting one number from another I get a false result. I could round the result with 2 decimals, but this is more a workaround.

Sub Test()
    Dim Sale As Double
    Dim Fee As Double
    Dim Payment As Double
    Payment = 104953.98
    Sale = 105000
    Fee = Sale - Payment
End Sub

Testing the code in the immediate window shows that Fee is calculated to 46,0200000000041 which is false.


Solution

Based on the naming of the variables you might want to try this

Sub Test()
    Dim Sale As Currency
    Dim Fee As Currency
    Dim Payment As Currency
    Payment = 104953.98
    Sale = 105000
    Fee = Sale - Payment
End Sub

You also should read on Floating-point arithmetic and https://floating-point-gui.de/



Answered By - Storax
Answer Checked By - Marilyn (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.