1

我在 Basic for LibreOffice 中的 ROUND 函数遇到了问题:

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

它返回小于 0.1 的 dNumber 值的科学记数法,而不是预期的四舍五入的十进制值。

示例: msgbox(Round(0.0333333, 2))

结果:3E-02.00 而不是预期的:0.03

谁能告诉我为什么会发生这种情况以及我在下面编写的解决方案是否是解决问题的正确方法,或者是否有更好的方法?

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

简化Round()函数的屏幕截图,用于以科学计数法Msgbox()输出3E-02的结果,而不是十进制的0.03的预期结果。

4

1 回答 1

0

在https://forum.openoffice.org/en/forum/viewtopic.php?f=13&t=66808中描述了在 LibreOffice Basic 中舍入的首选方式。

Function MyRound(dNumber As Double, iDecimals As Integer) As Double
   MyRound = Int(dNumber * 10 ^ iDecimals + 0.5) / 10 ^ iDecimals
End Function

输入=MYROUND(1/3,5)电子表格会产生0.33333.

于 2017-07-19T18:07:06.463 回答