简体   繁体   English

Excel VBA如何将双精度四舍五入为整数?

[英]How Excel VBA rounds Doubles to Integers?

I am trying to understand the type of errors that could happen when a wrong type of variable is declared in VBA. 我试图了解在VBA中声明错误类型的变量时可能发生的错误类型。

This is the code I am using: 这是我正在使用的代码:

Sub testTypes()

Dim test1 As Integer
test1 = 0.5

Debug.Print test1

End Sub

I tried to use Double number types on purpose to see how VBA will round them (up or down) to make them an Integer, given that the number ends on .5 考虑到数字以.5结尾,我试图使用Double数字类型来查看VBA如何将它们四舍五入(向上或向下)以使它们成为Integer。

I got puzzling results: 我得到令人困惑的结果:

5.567 --> 6
5.5 --> 6
4.5 --> 4
3.5 --> 4
2.5 --> 2
1.5 --> 2
0.5 --> 0

Could anyone explain how Excel determines whether it will round up or down? 谁能解释Excel如何确定它会向上舍入还是向下舍入?

In order to avoid so called banker's rounding (= midpoint value 5 always rounds to the nearest even number ) you can use 为了避免所谓的银行家舍入(=中点值5总是舍入到最接近的偶数),您可以使用

  • (1) WorkSheetFunction.Round (1) WorkSheetFunction.Round
  • (2) a user defined function. (2)用户自定义功能。

Banker's rounding is a standard form of rounding used in financial and statistical operations in order to minimize significant rounding errors over multiple rounding operations by consistently rounding midpoint values in a single direction. Banker的舍入是金融和统计操作中使用的标准舍入形式,目的是通过在单个方向上一致地舍入中点值来最大程度地减少多次舍入操作中的重大舍入误差。

(1) Example using the WorksheetFunction Round() (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) An alternative to the worksheet function (avoiding bankers' rounding): (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, it will round up or down depending if it is an even or odd number. 桑德拉(Sandra),根据它是偶数还是奇数,它会向上或向下取整。 If it is an even number, it will be round down. 如果是偶数,则将四舍五入。 Otherwise, it will round up. 否则,它将四舍五入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM