圆函数强制科学记数法而不是十进制

时间:2017-07-19 14:09:06

标签: decimal rounding libreoffice-calc scientific-notation libreoffice-basic

我在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(回合(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.

1 个答案:

答案 0 :(得分: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