如何处理 vb.net 中双打的舍入错误?
我正在尝试使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于财务计算,我相信当前的智慧是使用小数而不是双精度。
您可能对此讨论感兴趣 十进制与小数 双。
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.
尝试使用 Decimal 类型。
MSDN - 十进制
Try using the Decimal type.
MSDN - Decimal