如何在 VBA 中截断双精度数
How to Truncate a Double in VBA
我在 VBA 中有一个变量,我需要将其截断为 4 位有效数字。我似乎找不到任何不会向上或向下舍入数字的东西。但我只想删除第 4 位有效数字之后的数字。我试过了,
compressibility = round(compress, -3 - (Int(Log(Abs(compress)))))
它删除了第 4 位数字后的数字,但仍将数字四舍五入。
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 WorksheetFunction.RoundDown 方法而不是使用 VBA Round 函数来实现你需要的结果。
ROUNDDOWN(0.00024586548385;7)=0.000245800000
ROUNDDOWN(0.00024583548385;7)=0.000245800000
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
我在 VBA 中有一个变量,我需要将其截断为 4 位有效数字。我似乎找不到任何不会向上或向下舍入数字的东西。但我只想删除第 4 位有效数字之后的数字。我试过了,
compressibility = round(compress, -3 - (Int(Log(Abs(compress)))))
它删除了第 4 位数字后的数字,但仍将数字四舍五入。
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 WorksheetFunction.RoundDown 方法而不是使用 VBA Round 函数来实现你需要的结果。
ROUNDDOWN(0.00024586548385;7)=0.000245800000 ROUNDDOWN(0.00024583548385;7)=0.000245800000
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