by Brian Pierron (1 Submission)
Category: VB function enhancement
Compatability: Visual Basic 3.0
Difficulty: Intermediate
Date Added: Wed 3rd February 2021
Rating: (2 Votes)
The Visual Basic functions CByte(), CInt(), CLng(), CCur() and Round() user a Banker's Rounding algorithm. For example, VBA.Round(0.15,1) = 0.2 **AND** VBA.Round(0.25,1) = 0.2. The following code uses Symmetric Arithmetic Rounding (similar to the Excel Worksheet Round function) where Round(0.15,1) = 0.2 and Round(0.25,1) = 0.3. Also, precision is enhanced by passing the 'Number' parameter as variant and using CDec within the routine. This helps circumvent floating point limitations. To see an excellent resource on different rounding procedures (the basis for this code) see Microsoft Article ID: Q196652.
Public Function Round(Number As Variant, _
Optional NumDigitsAfterDecimal As Long) As Variant
If Not IsNumeric(Number) Then
Round = Number
Else
Round = Fix(CDec(Number * (10 ^ NumDigitsAfterDecimal)) + 0.5 * Sgn(Number)) / _
(10 ^ NumDigitsAfterDecimal)
End If
End Function