BudiBadu Logo
Samplebadu

COBOL by Example: PIC Clauses

COBOL 2002

Exploring advanced Picture clause features for signed numbers using S prefix, implementing implied decimal points with V for fixed-point arithmetic without storage overhead, creating display-formatted output with editing characters like dollar signs and commas, and understanding the difference between computational and display picture formats for numeric data processing.

Code

       IDENTIFICATION DIVISION.
       PROGRAM-ID. PIC-DEMO.
       
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  SINGLE-DIGIT    PIC 9.
       01  SIGNED-NUM      PIC S99 VALUE -15.
       01  DECIMAL-NUM     PIC 99V99 VALUE 12.34.
       01  FORMATTED-NUM   PIC $$,$$9.99 VALUE 1234.56.
       
       PROCEDURE DIVISION.
           MOVE 5 TO SINGLE-DIGIT.
           DISPLAY "Single: " SINGLE-DIGIT.
           DISPLAY "Signed: " SIGNED-NUM.
           DISPLAY "Decimal (Internal): " DECIMAL-NUM.
           DISPLAY "Formatted: " FORMATTED-NUM.
           STOP RUN.

Explanation

PIC clauses offer powerful features beyond simple types. They handle signed numbers, implied decimals, and display formatting. The S character in a PIC string (e.g., S99) indicates that the number is signed. Without it, all numbers are treated as positive, and any negative sign assigned to it will be lost.

The V character represents an implied decimal point. PIC 99V99 means the variable holds 4 digits, but the system treats it as having two decimal places. For example, the value 12.34 is stored as 1234. The decimal point does not take up any storage space; it is purely logical.

In this code example, we also use editing characters like $, ,, and .. A PIC string like $$,$$9.99 is used for presentation. It automatically inserts currency symbols, commas for thousands separators, and a physical decimal point. This feature makes generating reports in COBOL incredibly efficient.

Code Breakdown

7
PIC 9. A basic numeric field holding one digit. It is unsigned, so it can only hold 0-9.
8
PIC S99. The 'S' allows this variable to store negative numbers. '99' allows for values from -99 to +99. Internally, the sign is often stored in the last nibble of the byte.
9
PIC 99V99. Stores 12.34 as "1234". The 'V' tells the compiler to align decimal points correctly during math operations, even though the dot isn't stored.
10
PIC $$,$$9.99. This is an "edited" picture string. It is not used for math, but for display. It turns 1234.56 into "$1,234.56". The repeated '$' indicates a floating currency symbol.
16
DISPLAY "Decimal (Internal): " DECIMAL-NUM. This might print "1234" because the decimal is implied. To see "12.34", you would typically MOVE it to an edited field first.