I'm trying to balance a set of currency values using vb.net. The totals for both these values is cast as a double. I'm getting rounding errors in some situations.
What's the best way to avoid this? Is there a type I can use in preference to double? How do I round the resultant value to two decimal places?
Here's my code - I probably don't need to show it, but just in case.
Dim nInvValue As Double
Dim nCreditValue As Double
For Each oReferenceItem In oMatchInvoices
Dim nUnallocated As Double = oReferenceItem.DocumentOutstandingValue - oReferenceItem.DocumentAllocatedValue
If ((nUnallocated <> 0) And (sReferenceValue = oReferenceItem.InstrumentNo)) Then
iCount = iCount + 1
If (oReferenceItem.IsDebit) And (nUnallocated > 0) Then
nInvValue = nInvValue + nUnallocated
InvoiceList.Add(nUnallocated.ToString("c"), oReferenceItem.URN.ToString)
End If
If (oReferenceItem.IsCredit) And (nUnallocated < 0) Then
nCreditValue = nCreditValue - nUnallocated
CreditList.Add(nUnallocated.ToString("c"), oReferenceItem.URN.ToString)
End If
End If
Next