PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197
VB6 - Format Significant Figures-VBForums
Results 1 to 1 of 1

Thread: VB6 - Format Significant Figures

  1. #1

    Thread Starter
    Frenzied Member agmorgan's Avatar
    Join Date
    Dec 2000
    Location
    Lurking
    Posts
    1,383

    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:
    1. 'Returns input number rounded to specified number of significant figures.
    2. Function FormatSF(dblInput As Double, intSF As Integer) As String
    3.  
    4. Dim intCorrPower As Integer         'Exponent used in rounding calculation
    5. Dim intSign As Integer              'Holds sign of dblInput since logs are used in calculations
    6.  
    7. '-- Store sign of dblInput --
    8. intSign = Sgn(dblInput)
    9.  
    10. '-- Calculate exponent of dblInput --
    11. intCorrPower = Int(Log10(Abs(dblInput)))
    12.  
    13. FormatSF = Round(dblInput * 10 ^ ((intSF - 1) - intCorrPower))   'integer value with no sig fig
    14. FormatSF = FormatSF * 10 ^ (intCorrPower - (intSF - 1))         'raise to original power
    15.  
    16.  
    17. '-- Reconsitute final answer --
    18. FormatSF = FormatSF * intSign
    19.  
    20. '-- Answer sometimes needs padding with 0s --
    21. If InStr(FormatSF, ".") = 0 Then
    22.     If Len(FormatSF) < intSF Then
    23.         FormatSF = Format(FormatSF, "##0." & String(intSF - Len(FormatSF), "0"))
    24.     End If
    25. End If
    26.  
    27. If intSF > 1 And Abs(FormatSF) < 1 Then
    28.     Do Until Left(Right(FormatSF, intSF), 1) <> "0" And Left(Right(FormatSF, intSF), 1) <> "."
    29.         FormatSF = FormatSF & "0"
    30.     Loop
    31. End If
    32.  
    33.  
    34. End Function
    35.  
    36. 'Calculate Log to the Base 10
    37. Function Log10(x)
    38.    Log10 = Log(x) / Log(10#)
    39. End Function
    Usage
    VB Code:
    1. MsgBox FormatSF(6.8437, 2)
    2. Returns 6.8
    3. MsgBox FormatSF(1.0000326, 3)
    4. Returns 1.00
    5. MsgBox FormatSF(6345.8437, 2)
    6. Returns 6300

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width