|
RPG
Developer Network News |
|
Tuesday, July 4, 2000 |
Editor: Robert Cozzi, Jr. |
CharToNum
Made Easier
Using the Free C runtime library to
convert char to numeric better
Using the C2N or CharToNum procedures to convert character strings containing numbers into numeric variables is wide spread. These two procedures, C2N written by Mel Rothman of IBM at www.easy400.ibm.it and CHARTONUM, written by Bob Cozzi (that's me) use RPG IV to parse a character value, and turn it into a number.
Fortunately we don't have to use each of these relatively slow routines, because IBM already provides us with built-in procedures to do this. It is, as always, the C language runtime library to the rescue.
The C language's atoi (for "ASCII to Integer") and atof (for "ASCII to Floating point value") accept a character string value, parse it, and translate it into either an integer ( 4-byte binary to us old RPG coders) or into a Floating point.
Listed below is the Prototype RPG IV source needed to call the C runtime routines. You can /COPY or physically copy this code into your RPG IV CGI programs, and use it to do things like get the CONTENT_LENGTH value (which is returned as a character string).
To call either of these routines, use the EVAL statement, and pass a normal character string variable as the first and only parameter. If the floating point version does not return the data rounded correctly, try wrapping that value in %DECH and/or using the EVAL(H) [eval with half-adjust].
Deciding which of the two routines to use is easy. If the desired result should contain decimal positions, use the ATOF procedure, if the result should have no decimals, use the ATOI procedure. For example, ATOI would be used to retrieve the CONTENT_LENGTH in a CGI program.
**
RPG IV Prototypes for C runtime library Math functions.
**
If NUMVAL is Pkd(7,2), then:
**
NumVal = atof('1234.56') // results is NumVal=1234.56
**
NumVal = atoi('1234') // results is NumVal=1234
D
atof
PR
8F
Extproc('atof')
D
dValue
*
VALUE
Options(*STRING)
D
atoi
PR
10i
0
Extproc('atoi')
D
iValue
*
VALUE Options(*STRING)