Function dblRound(ByVal vdblNumber As Double, ByVal vintDecimalPlaces As Integer) As Double
Dim dblWholePart As Double
Dim dblRemainder As Double
Dim dblDecimalMultiplier As Double
On Error GoTo ErrorHandler
Here's one that works well - it's widely posted on the web.
Public Function BankersRounding(ByVal Number As Variant, NumDigits As Long, Optional UseBankersRounding As Boolean = False) As Double
Dim dblPower As Double
Dim varTemp As Variant
Dim intSgn As Integer
If Not IsNumeric(Number) Then
' Raise an error indicating that
' you've supplied an invalid parameter.
Err.Raise 5
End If
dblPower = 10 ^ NumDigits
' Is this a negative number, or not?
' intSgn will contain -1, 0, or 1.
intSgn = Sgn(Number)
Number = Abs(Number)
'Do the major calculation.
varTemp = CDec(Number) * dblPower + 0.5
'Now round to nearest even, if necessary.
If UseBankersRounding Then
If Int(varTemp) = varTemp Then
' You could also use:
' varTemp = varTemp + (varTemp Mod 2 = 1)
' instead of the next If ...Then statement,
' but I hate counting on TRue == -1 in code.
If varTemp Mod 2 = 1 Then
varTemp = varTemp - 1
End If
End If
End If
'Finish the calculation.
BankersRounding = intSgn * Int(varTemp) / dblPower
End Function
'Example of usage would be.
'cTranAmt = BankersRounding(cTranAmt, 2)
'which would round the value to two decimal places
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.