BruceM said:
I have become interested in a topic that was not even on my radar a week
ago, so I will continue to monitor this thread. At the least I will learn
something more about VBA.
First I changed SetSF to be able to handle non-positive numbers:
'-----Begin Module Code
Public Function SetSF(dblX As Double, intSF As Integer) As Double
Dim dblMantissa As Double
Dim intExponent As Integer
Dim dblSP As Double
Dim intSign As Integer
SetSF = 0
If dblX = 0 Then Exit Function
intSign = 1
If dblX < 0 Then
dblMantissa = Log(-dblX) / Log(10#)
intSign = -1
Else
dblMantissa = Log(dblX) / Log(10#)
End If
intExponent = Int(dblMantissa)
dblMantissa = dblMantissa - intExponent
dblSP = 10 ^ dblMantissa
dblSP = Round(dblSP, intSF - 1)
SetSF = intSign * dblSP * 10 ^ intExponent
End Function
Public Function FormatSF(dblX As Double, intPlaces As Integer) As String
Dim intExponent As Integer
Dim intSign As Integer
Dim strTemp As String
If dblX <> 0 Then
If dblX < 0 Then
intExponent = Int(Log(-dblX) / Log(10) + 0.0000001)
Else
intExponent = Int(Log(dblX) / Log(10) + 0.0000001)
End If
intSign = Sgn(dblX)
If Int(dblX) = dblX And intPlaces > intExponent + 1 Then
FormatSF = CStr(dblX) & "." & String(intPlaces - intExponent - 1, "0")
Else
FormatSF = CStr(dblX)
End If
Else
strTemp = "0"
If intPlaces > 1 Then
strTemp = strTemp & "." & String(intPlaces - 1, "0")
End If
FormatSF = strTemp
End If
End Function
'-----End Module Code
Test situations:
FormatSF(SetSF(100, 1), 1) = "100"
FormatSF(SetSF(100, 2), 2) = "100"
FormatSF(SetSF(100, 3), 3) = "100"
FormatSF(SetSF(100, 4), 4) = "100.0"
FormatSF(SetSF(12, 2), 2) = "12"
FormatSF(SetSF(12, 3), 3) = "12.0"
FormatSF(SetSF(3, 4), 4) = "3.000"
FormatSF(SetSF(30, 4), 4) = "30.00"
FormatSF(SetSF(300, 4), 4) = "300.0"
FormatSF(SetSF(3000, 4), 4) = "3000"
FormatSF(SetSF(5, 1), 1) = "5"
FormatSF(SetSF(5, 2), 2) = "5.0"
FormatSF(SetSF(2120, 4), 4) = "2120"
FormatSF(SetSF(32200, 5), 5) = "32200"
FormatSF(SetSF(32222, 5), 5) = "32222"
Those were the only examples I tried. I didn't try the cases where the
input is 0. I didn't try the cases where the input is negative. I
didn't like having to use '+ 0.0000001' to keep a value whose internal
representation is barely under an integer from being chopped. Creating
a version of FormatSF using SQL looks too messy but hopefully that's not
too much of a restriction. Hopefully I'll get to your questions soon.
If your numbers are already set to the correct number of scientific
figures you shouldn't need the SetSF function, just the FormatSF
function. I'll try to explain the SetSF function in a simple way. Let
me know if you discover any situations not covered by these functions.
James A. Fortune
(e-mail address removed)