1

我與ROUND函數基本爲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 

它返回上dNumber值是不是圓的小於0.1科學記數法預期的十進制值。

例: MSGBOX(圓形(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 

Screenshot of simplified Round() function using Msgbox() to output the result of 3E-02 in Scientific Notation instead of the expected result of 0.03 in decimal.

+0

'Round'對於你的函數來說不是一個好名字,因爲它與內置函數相同。 –

回答

0

圓中的LibreOffice Basic中的優選方式在https://forum.openoffice.org/en/forum/viewtopic.php?f=13&t=66808進行說明。

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

相關問題