Extract Numerics from Text


EXTNUM is a dBase IV function, called from a procedure file, which evaluates 
the first numeric encountered in a text string and returns its value.  The 
EXTNUM function can be used to extract values from verbose text listings for 
further processing. As written the function will correctly ignore embedded 
commas, and will return a negative value if the preceding punctuation mark 
is a hyphen.  dBase rounds output to the 'Set Decimals To value', but 
retains correct internal accuracy.  This procedure is placed in the public 
domain by the author.

Examples of Use from the dBase command line:

dBase>? extnum("The equatorial diameter of the earth is about 7,926.406 miles")
      7926.40

dBase>? extnum("Absolute zero is -273.16 degrees Centigrade")
      -273.16

CUT HERE
*****************************************************************************
*       Function: EXTNUM()                && EXTNUM is passed a text string
*       Pete Rushworth -- CIS 71777,226   Public Domain dBase Procedure
*****************************************************************************
FUNCTION extnum
PARAMETERS str        
PRIVATE numstr,digits,endstr,nflag,negflag,spt
numstr=""
digits="0123456789"
endstr=len(rtrim(str))
nflag=.f.
negflag=.f.
spt=1

DO WHILE spt<=endstr                      && Main Loop -- Extract digits and punctuation 
                                          && within numeric strings
    IF substr(str,spt,1) $ digits .or. (nflag.and.substr(str,spt,1) $ ".,")
        numstr=numstr+substr(str,spt,1)
        IF .not.nflag                     && Evaluate char prior to first number 
            IF substr(str,spt-1,1)="-"    && for negation.  Assumes preceding '-'  
                negflag=.t.               && is a negator.
            ENDIF
        ENDIF
        nflag=.t.
    ELSE
        IF nflag                          && Close loop on first non-numeric
            spt=endstr                    && after evaluation
        ENDIF
    ENDIF
    spt=spt+1
ENDDO

DO while "," $ numstr                     && Remove embedded commas
    numstr=stuff(numstr,at(",",numstr),1,"")
ENDDO

IF negflag                                && Negate
    numstr="-"+numstr
ENDIF
release digits,spt,nflag,endstr,negflag,str
RETURN val(numstr)
                                                   
