I am doing a simple calculation in VB.Net, following is the code.
Dim total As String = "192.04"
Dim paid As String = "200"
Dim change As String = "7.96"
'//This prints -7.99360577730113E-15 (Incorrect)
MsgBox((CDbl(total) - CDbl(paid)) + CDbl(change))
The answer I expect from this calculation is 0 but I get -7.99360577730113E-15. I don't know the exact reason for this, I couldn't quite understand the reason explained on MSDN. Any clarification would be really helpful.
And I did a Math.Round to 2 decimal places & the problem was solved, therefore do I need to use Math.Round everywhere I do a calculation with decimals ?
That's because of how double
(or floating point numbers in general) is represented in memory. You should use decimal
for financial calculations instead of double
:
double total = 192.04;
double paid = 200;
double change = 7.96;
double result = (total - paid) + change; // -7.99360577730113E-15
decimal total = 192.04m;
decimal paid = 200m;
decimal change = 7.96m;
decimal result = (total - paid) + change; // 0.00
I know it's C#, but you should see the difference anyway.
You can use Decimal.Parse
to get a decimal
from string
:
Dim total As String = "192.04"
Dim paid As String = "200"
Dim change As String = "7.96"
MsgBox((Decimal.Parse(total) - Decimal.Parse(paid)) + Decimal.Parse(change))