爲了避免所謂的銀行家舍入(=中點值5總是舍入到最接近的偶數),可以使用
- (1)
WorkSheetFunction.Round
- (2)的用戶定義的函數。
銀行家的舍入是在財務和統計操作中使用的舍入的標準形式,以便通過在單個方向上持續舍入中點值來最大限度地減少多次舍入操作中的重大舍入誤差。
(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如果你想強制向上或向下舍入,你可以使用'WorksheetFunction.RoundUp(test1,0)'(或'RoundDown',語法相同)。 –
嗨@ScottCraner感謝您提出問題!我覺得這個定義,我發現使它更加清晰:。 「這圍捕時,前5位爲奇數如果它甚至是幾輪下來 例 1.1235回合1.124 1.1225回合1.122 – Sandra