【问题标题】:How do I cope with rounding errors on doubles in vb.net?如何处理 vb.net 中双精度数的舍入错误?
【发布时间】:2010-09-16 05:55:42
【问题描述】:

我正在尝试使用 vb.net 平衡一组货币价值。这两个值的总和被转换为双精度值。在某些情况下,我会遇到舍入错误。

避免这种情况的最佳方法是什么?有没有一种我可以优先使用的类型?如何将结果值四舍五入到小数点后两位?

这是我的代码 - 我可能不需要展示它,但以防万一。

  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

【问题讨论】:

    标签: vb.net rounding-error


    【解决方案1】:

    尝试使用 Decimal 类型。

    MSDN - Decimal

    【讨论】:

      【解决方案2】:

      对于财务计算,我认为目前的智慧是使用小数而不是双精度数。

      您可能对此讨论感兴趣Decimal Vs. Double

      【讨论】:

        猜你喜欢
        • 2019-09-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-08
        • 2015-06-12
        • 1970-01-01
        相关资源
        最近更新 更多