' all the framework rounding methods use banker's rounding
' if a number is exactly halfway between two numbers, it will round to the nearest even
' i.e. - 3.5 will round to 4, but 2.5 will round to 2
Function Round(ByVal dVal As Decimal, ByVal lScale As Int32) As Decimal
Dim lMltply As Int32
Dim dAdd As Decimal
' find half of the least significant digit
dAdd = CType(Math.Pow(0.1, lScale) * 0.5, Decimal)
If dVal < 0 Then dAdd *= -1
' initialize multiplier
lMltply = CType(Math.Pow(10, lScale), Int32)
' add half of the least significant digit, times the multiplier, truncate,
' and divide by the multiplier
Return Decimal.Truncate((dVal + dAdd) * lMltply) / lMltply
End Function
|