Friday, June 11, 2010

Retain Leading Zeros in RPG with Edit Codes

This built in function is probably not new to most, but I found it very helpful recently.

I had to pull a numeric field out of DB2 and convert it to characters while retaining the leading zeros.  I received a little tip on how to do this using the %editc BIF.  Note that shiptime is the DB2 field and chartime is the variable.

The “X” edit code is used to keep leading zeros.  Cute function.

/free
evalr chartime = %editc(shiptime:’X’)
/end-free

2 comments:

  1. The zoned decimal value -5 stored in a S(4, 0) field or variable as hex data x'F0F0F0D5' would be presented as the string '000N' using the 'X' edit code. I prefer an edit word.

    DSTR S 40A varying
    DS4 S 4S00
    /free
    s4=-5;
    str='EDTC(X):' + %editc(s4 : 'X') + ' EDTW:' + %editw(s4 : '0 ') +
    ' EDTW-:' + %editw(s4 : '0 -');
    dsply STR;
    *inlr = *on;
    /end-free

    CALL ABOVEPGM /* following output: */
    DSPLY EDTC(X):000N EDTW: 0005 EDTW-: 0005-

    ReplyDelete
  2. Anonymous, you make a valid point but IMHO edit words are not very intuitive. The basic point is that editc makes the process conversion simple. Long live RPG. With many ways to skin a cat, here's just one other way to handle negatives:
    if number < 0;
    number = %abs(number);
    sign = '-';
    endif;
    eval text = sign + %editc(number:'X');

    ReplyDelete