How Excel VBA rounds Doubles to Integers?

后端 未结 2 880
清酒与你
清酒与你 2021-01-19 04:15

I am trying to understand the type of errors that could happen when a wrong type of variable is declared in VBA.

This is the code I am using:

Sub t         


        
相关标签:
2条回答
  • 2021-01-19 04:36

    Sandra, it will round up or down depending if it is an even or odd number. If it is an even number, it will be round down. Otherwise, it will round up.

    0 讨论(0)
  • 2021-01-19 04:44

    In order to avoid so called banker's rounding (= midpoint value 5 always rounds to the nearest even number ) you can use

    • (1) WorkSheetFunction.Round
    • (2) a user defined function.

    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.

    (1) Example using the 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):

    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
    
    0 讨论(0)
提交回复
热议问题