April 2006 Technical Tip COBOL: Did you remember to test for numerics?

When performing data validation on zoned decimal numeric fields in COBOL, always check for NUMERIC. Never rely upon IFs and 88s alone! This article will demonstrate why.

I love 88s (condition names.) I often tell my students that I find them to be one of the nicest features in COBOL. But IF statements, with or without 88s, when performed on zoned decimal numeric fields, disregard the sign bits of all but the last digit. Consequently, it is possible to have a non-numeric character, such as any letter of the alphabet, in a supposed numeric field, and that field be treated as a number. IFs and 88s wont catch the error. However, at least to my knowledge, COBOLs check for NUMERIC cannot be fooled. Consider the following example

DATA DIVISION.
WORKING-STORAGE SECTION.
01  MISC.
    05  INPUT-FLD-AS-X      PIC X(5).
    05  INPUT-FLD-AS-9  REDEFINES  INPUT-FLD-AS-X  PIC 9(3)V99.
        88  VALID-VALUES    VALUE 100 THRU 199.99.
    05  OUTPUT-FLD-AS-Z     PIC ZZ9.99.


Given: MOVE '13E79' TO INPUT-FLD-AS-X
then:  IF INPUT-FLD-AS-9 IS NUMERIC  is false
but:   IF VALID-VALUES  is true
and:   IF INPUT-FLD-AS-9 >= 100 AND INPUT-FLD-AS-9 <= 199.99  is true
and:   MOVE INPUT-FLD-AS-9 TO OUTPUT-FLD-AS-9  gives 135.79

The reason for this is that C13E79 is equivalent to XF1F3C5F7F9 and when COBOLs IF looks at a zoned decimal field, it ignores the zone bits (XF and XC) in all but the rightmost byte. Indeed, the COBOL compiler will generate a machine level PACK instruction for the purpose of the compare (since zoned decimal instructions do not exist at the machine level) and this value packs to X13579F, which is a valid packed decimal numeric field.

So you should never rely upon a range check alone (with or without an 88.) The data could be properly checked as follows: IF INPUT-FLD-AS-9 IS NUMERIC AND VALID-VALUES

You can download the source code here and download the results here. Technical note: The example contained herein was done using IBM COBOL for OS/390 & VM 2.1.1.

We at Caliber Data Training have a long history of providing COBOL training. All of our COBOL instructors are experienced COBOL programmers. We hope you will consider Caliber Data Training when you are in need of a COBOL training provider.


Go to the articles index. Written by Bill Qualls. Copyright © 2006 by Caliber Data Training 800.938.1222