Forum Guidelines

This forum is for finished source code that is working properly. If you have questions about this or any other source code, please post it in one of the Discussion Forums, not here.
See more
See less

Engineering suffix conversion

  • Filter
  • Time
  • Show
Clear All
new posts

  • Engineering suffix conversion

    Below two functions are presented for the conversion of numerical values to engineering suffix notation (values like 22p, 3.3n or 100K), and vice versa. The functions are quite simple.

    In spite of this, the SuffixInput function accepts equally well regular and scientific notation, and can therefore be used as an input handler with extended capacities.

    This code was originally posted on the Programming forum.

    Arie Verheul

    Function SuffixInput (InputString As Asciiz) As Single
        ' Function accepts regular notation, scientific notation,
        ' and suffices "atto" through "Tera", and returns them as a numerical value.
        Local I As Integer, Suffix As String*1
        Replace "k" With "K" In Inputstring      ' Often "K" is incorrectly written lowercase
        I = InStr (InputString, Any "afpnumKMGT")
        If I Then
            Suffix = Mid$(InputString, I, 1)
            I = InStr("afpnum KMGT", Suffix) - 7
        End If
        Function = Val(InputString) * 1000^I
    End Function
    Function SuffixOutput (Value As Single) As String
        ' Function returns Value using engineering suffix
        ' if it is in the range between 1 atto and 999 Tera,
        ' outside this range Value is returned in Scientific notation
    Local L, NumValue As Single, I As Integer, Suffix As String*1
        Select Case Abs(Value)
            Case 0                   : Function = "0 "
            Case  < 1e-18, > 9.99e14 : Function = Using$ ("##.##^^^^ ",Value)
            Case Else
                L = Log10 (Abs(Value))
                I = Fix (1e-6 + L /3)       ' Add the uncertainty for proper truncation
                                            ' This has no effect on accuracy
                If L < 0 Then Decr I
                NumValue = Value / 1000^I               ' Numerical part of output
                Suffix = Mid$("afpnum KMGT", I + 7, 1)  ' Alphanumerical part of output
                Function = (Using$("##.# ",NumValue)) + Suffix
        End Select
    End Function