[英]How Excel VBA rounds Doubles to Integers?
我试图了解在VBA中声明错误类型的变量时可能发生的错误类型。
这是我正在使用的代码:
Sub testTypes()
Dim test1 As Integer
test1 = 0.5
Debug.Print test1
End Sub
考虑到数字以.5结尾,我试图使用Double数字类型来查看VBA如何将它们四舍五入(向上或向下)以使它们成为Integer。
我得到令人困惑的结果:
5.567 --> 6
5.5 --> 6
4.5 --> 4
3.5 --> 4
2.5 --> 2
1.5 --> 2
0.5 --> 0
谁能解释Excel如何确定它会向上舍入还是向下舍入?
为了避免所谓的银行家舍入(=中点值5总是舍入到最接近的偶数),您可以使用
WorkSheetFunction.Round
Banker的舍入是金融和统计操作中使用的标准舍入形式,目的是通过在单个方向上一致地舍入中点值来最大程度地减少多次舍入操作中的重大舍入误差。
(1)使用WorksheetFunction Round()
示例
Sub RoundWithWorkSheetFunction()
' Purpose: avoid so called bankers' rounding in VBA (5 always rounds even)
With WorksheetFunction
Debug.Print "WorksheetFunction.Round(3.5, 0)=" & .Round(3.5, 0), ":| VBA rounds to " & Round(3.5, 0)
Debug.Print "WorksheetFunction.Round(4.5, 0)=" & .Round(4.5, 0), ":| VBA rounds to " & Round(4.5, 0)
End With
End Sub
(2)工作表功能的替代方法(避免四舍五入)。
Function roundIt(ByVal d As Double, ByVal nDigits As Integer) As Double
' Purpose: avoid so called bankers' rounding in VBA (5 always rounds even)
If nDigits > 0 Then
' if continental european colon instead of point separartor
' roundIt= val(Replace(Format(d, "0." & String(nDigits, "0")), ",", "."))
roundIt = Val(Format(d, "0." & String(nDigits, "0")))
Else
' if continental european colon instead of point separartor
' roundIt = val(Replace(Format(d / (10 ^ nDigits), "0."), ",", "."))
roundIt = Val(Format(d / (10 ^ nDigits), "0."))
End If
End Function
桑德拉(Sandra),根据它是偶数还是奇数,它会向上或向下取整。 如果是偶数,则将四舍五入。 否则,它将四舍五入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.