如何在VBA中截断Double

如何在VBA中截断Double,vba,excel,truncate,Vba,Excel,Truncate,在VBA中有一个变量,我需要将其截断为4位有效数字。我似乎找不到任何不能使数字向上或向下舍入的东西。但是我只想删除第四个有效数字之后的数字。我已经试过了 compressibility = round(compress, -3 - (Int(Log(Abs(compress))))) 它删除第四位之后的数字,但仍将数字向上舍入 例如,Compress是一个大约为0.000245848385的数字,我需要压缩系数为0.0002458 任何建议都很好!谢谢。使用工作表功能: =VALUE(TEXT

在VBA中有一个变量,我需要将其截断为4位有效数字。我似乎找不到任何不能使数字向上或向下舍入的东西。但是我只想删除第四个有效数字之后的数字。我已经试过了

compressibility = round(compress, -3 - (Int(Log(Abs(compress)))))
它删除第四位之后的数字,但仍将数字向上舍入

例如,Compress是一个大约为0.000245848385的数字,我需要压缩系数为0.0002458


任何建议都很好!谢谢。

使用工作表功能:

=VALUE(TEXT(compress,"0.000E+00"))
对于VBA

CDbl(Format(compress,"0.000E+00"))
希望有帮助。

尝试此功能:

Function RoundSignificant(ByVal dValue As Double, iFigures As Integer)
    Dim dSig As Double
    dSig = Abs(dValue)
    dSig = Application.Log10(dSig)
    dSig = 1 + Int(dSig)
    dSig = iFigures - dSig
    RoundSignificant = Round(dValue, dSig)
End Function


Sub test()
    Debug.Print RoundSignificant(0.000245848385, 4)
End Sub

在我看来,您希望避免四舍五入,而不是四舍五入,因为四舍五入应该会产生您想要的确切结果。因此,您可以使用Excel工作表函数.RoundDown方法来实现所需的结果,而不是使用VBARound函数

四舍五入(0.00024586548385;7)=0.000245800000
四舍五入(0.00024583548385;7)=0.000245800000

如果您只是将
-3
更改为
-2
,会怎么样?这会给我太多的有效数字5而不是4不幸的是,VBA选项也会将最终值向上舍入,而不仅仅是删除后面的数字,因此效果非常好,只要第5个数字小于5。除此之外,第四个数字仍然是四舍五入。如果我有0.000028348,它会将其更改为0.00002835,而不是0.00002834将
Round
更改为
Application.RoundDown
Sub test()
Dim compress As Double
compress = 0.000245858

Dim compressibility As Double
compressibility = Int(compress * 10 ^ -(Int(Log(Abs(compress))) - 3)) / 10 ^ -(Int(Log(Abs(compress))) - 3)

Debug.Print compressibility
End Sub