如何处理 vb.net 中双打的舍入错误?

发布于 2024-07-06 14:00:28 字数 988 浏览 6 评论 0原文

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

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

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

  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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

愿与i 2024-07-13 14:00:28

对于财务计算,我相信当前的智慧是使用小数而不是双精度。

您可能对此讨论感兴趣 十进制与小数 双

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.

带刺的爱情 2024-07-13 14:00:28

尝试使用 Decimal 类型。

MSDN - 十进制

Try using the Decimal type.

MSDN - Decimal

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文