M
Michiel via OfficeKB.com
Hi all,
This rounding issue in VBA drive me crazy!
Many posts report that VBA uses the bankers rounding. But I need the standard
rounding.
So I tried to make my own Mathematical Rounding function. For some
mysterieous reasons it does not always work as expected.
Anyone who likes solving strange behaviour of VBA is kindly invited to see
why.
MathRound(101.68000000000001,5) works OK --> 101.68000
MathRound(102.63000000000001,5) does not work ---> 102.63001 (102.63000
expected)
The function:
Function MathRound(dblInput As Double, intDigits As Integer) As Double
'Rounds the input value (DblInput) to the number of digits specified in
intDigits
'The container values dblContainer and dblContner seem to be necessary
because
'without them the calculations are wrongly passed through.
Dim dblContainer As Double
Dim lngExpon As Long
Dim lngLong As Long
Dim dblContner As Double
dblContainer = dblInput + 5 * (10 ^ -(intDigits + 1)) 'Add a bit to make
sure truncation is done right.
lngExpon = 10 ^ intDigits 'calculate the power of ten to be multiplied
based on the number of digits
dblContner = Round(dblContainer * lngExpon, 0) 'PUT value in second
container
lngLong = Fix(dblContner) 'truncate value
MathRound = lngLong / lngExpon 'Devide back to the correct number of
digits
End Function
Thanks!
This rounding issue in VBA drive me crazy!
Many posts report that VBA uses the bankers rounding. But I need the standard
rounding.
So I tried to make my own Mathematical Rounding function. For some
mysterieous reasons it does not always work as expected.
Anyone who likes solving strange behaviour of VBA is kindly invited to see
why.
MathRound(101.68000000000001,5) works OK --> 101.68000
MathRound(102.63000000000001,5) does not work ---> 102.63001 (102.63000
expected)
The function:
Function MathRound(dblInput As Double, intDigits As Integer) As Double
'Rounds the input value (DblInput) to the number of digits specified in
intDigits
'The container values dblContainer and dblContner seem to be necessary
because
'without them the calculations are wrongly passed through.
Dim dblContainer As Double
Dim lngExpon As Long
Dim lngLong As Long
Dim dblContner As Double
dblContainer = dblInput + 5 * (10 ^ -(intDigits + 1)) 'Add a bit to make
sure truncation is done right.
lngExpon = 10 ^ intDigits 'calculate the power of ten to be multiplied
based on the number of digits
dblContner = Round(dblContainer * lngExpon, 0) 'PUT value in second
container
lngLong = Fix(dblContner) 'truncate value
MathRound = lngLong / lngExpon 'Devide back to the correct number of
digits
End Function
Thanks!