views:

652

answers:

2

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
+2  A: 

Try using the Decimal type.

MSDN - Decimal

JTA
+3  A: 

For financial calculations I believe that the current wisdom is to use Decimals instead of Doubles.

You might be interested in this discussion Decimal Vs. Double.

TK