VB6 - Format Significant Figures
Visual Basic lacks a function to round to a specified number of significant figures.
The first significant figure of a value is the first non-zero number.
e.g. 0.0000054034
After the first significant figure, subsequent zeros become significant.
e.g. 0.0000054034 to 3sf is 0.00000540
VB Code:
'Returns input number rounded to specified number of significant figures.
Function FormatSF(dblInput As Double, intSF As Integer) As String
Dim intCorrPower As Integer 'Exponent used in rounding calculation
Dim intSign As Integer 'Holds sign of dblInput since logs are used in calculations
'-- Store sign of dblInput --
intSign = Sgn(dblInput)
'-- Calculate exponent of dblInput --
intCorrPower = Int(Log10(Abs(dblInput)))
FormatSF = Round(dblInput * 10 ^ ((intSF - 1) - intCorrPower)) 'integer value with no sig fig
FormatSF = FormatSF * 10 ^ (intCorrPower - (intSF - 1)) 'raise to original power
'-- Reconsitute final answer --
FormatSF = FormatSF * intSign
'-- Answer sometimes needs padding with 0s --
If InStr(FormatSF, ".") = 0 Then
If Len(FormatSF) < intSF Then
FormatSF = Format(FormatSF, "##0." & String(intSF - Len(FormatSF), "0"))
End If
End If
If intSF > 1 And Abs(FormatSF) < 1 Then
Do Until Left(Right(FormatSF, intSF), 1) <> "0" And Left(Right(FormatSF, intSF), 1) <> "."
FormatSF = FormatSF & "0"
Loop
End If
End Function
'Calculate Log to the Base 10
Function Log10(x)
Log10 = Log(x) / Log(10#)
End Function
Usage
VB Code:
MsgBox FormatSF(6.8437, 2)
Returns 6.8
MsgBox FormatSF(1.0000326, 3)
Returns 1.00
MsgBox FormatSF(6345.8437, 2)
Returns 6300