I’ve run into an issue with the ROUND function when coding a macro in Basic:
Function Round(dNumber As Double, iDecimals As Integer) As Variant
Dim oRound As Object
Dim vArgs(1 to 2) As Variant
oRound = createUnoService("com.sun.star.sheet.FunctionAccess")
vArgs(1) = dNumber
vArgs(2) = iDecimals
Round = oRound.callFunction("round", vArgs())
End Function
It returns Scientific Notation on dNumber values that are less than 0.1 instead of the rounded decimal value that’s expected.
EXAMPLE:
msgbox(Round(0.0333333, 2))
Results in:
3E-02.00
instead of the expected: 0.03
Can anyone tell me why this is occuring and if the solution that I’ve written below is the correct way of getting around the problem or if there’s a better way?
Function Round(dNumber As Double, iDecimals As Integer) As Variant
Dim oRound As Object 'Round function object
Dim dCompNumber As Double 'Store the Compensated value of dNumber
Dim dResult As Double 'Result of the rounding to be passed
Dim vArgs(1 to 2) As Variant 'Arguments: Number to be rounded, Number of decimal places
dCompNumber = dNumber 'Copy dNumber
oRound = createUnoService("com.sun.star.sheet.FunctionAccess")
'Get access to the library that contains the Round() function
'Compensate for Scientific Notation that occurs with numbers less than 0.1
If dNumber < 0.1 Then dCompNumber = dNumber + 1 ' Add 1 to temporarily increase value > 0.1
vArgs(1) = dCompNumber
vArgs(2) = iDecimals
dResult = oRound.callFunction("round", vArgs())
'Remove the Compensation for Scientific Notation
If dNumber < 0.1 Then dResult = dResult - 1 'Subtract 1 from the temporary value so that it is back to < 0.1
Round = dResult
End Function