COMP-3 | Packed-decimal


Tip! COMP-3 applies to the Numeric Data type.

COMP-3 (or Packed Decimal or Packed Numeric) is a convenient way to represent and store decimal numbers in a compact binary-coded decimal (BCD) format, which is efficient for arithmetic operations.

Storage Size and Format -

COMP-3 stores each digit of a number in 4 bits (half a byte) and uses an additional 4-bit at the end to store the sign (C for positive and D for negative). For example - the decimal number +123 is stored as 123C, and -123 is stored as 123D.

COMP-3 variable can contain digits 0 through 9, a sign. COMP-3 can have a value not exceeding 18 decimal digits.

Efficient Use of Memory -

Digits in PICTURE clauseStorage occupied
1 digit½ Byte

COMP-3 is efficient in terms of memory usage. For example - a COMP-3 field with a PIC S9(5) (which can store a number from -99999 to +99999) uses only 3 bytes of storage: 2.5 bytes for the digits and 0.5 bytes for the sign.

The formula for memory calculation of the COMP-3 with n digits in the declaration is -

  • No. of bytes = Round ((n + 1)/2) - Where n is an odd number.
  • No. of bytes = Round (n/2) - Where n is an even number.

Definition in a COBOL Program -

PICTURE clause required for COMP-3 declaration. We use the USAGE IS COMP-3 clause in the DATA DIVISION to declare a COMP-3 variable. For example -

01 WS-PDN     PIC 9(5) USAGE IS COMP-3.

In this example, WS-PDN is a variable with a five-digit decimal number in COMP-3 packed format.

Assigning Values to a COMP-3 Variable -

We can assign values to a COMP-3 variable like any other numeric variable in COBOL. For example -

MOVE 12345 TO WS-PDN.

Arithmetic Operations -

We can perform all arithmetic operations (add, subtract, multiply, divide, etc.) on COMP-3 variables like other numeric variables. For example -

ADD 100 TO WS-PDN.

Practical Example -


Scenario - Defining, initializing, its usage and display of COMP-3 variables.

Code -

----+----1----+----2----+----3----+----4----+----5----+
       ...
       WORKING-STORAGE SECTION.
       01 WS-VAR.
          05 WS-WIDTH        PIC S9(02) USAGE IS COMP-3.
          05 WS-AREA         PIC S9(06) COMP-3. 
       ...
       PROCEDURE DIVISION.
           MOVE 10            TO WS-WIDTH.
           COMPUTE WS-AREA =  WS-WIDTH ** 2.

           DISPLAY "LENGTH OF WS-AREA VARIABLE: "
                    LENGTH OF WS-AREA.
           DISPLAY "AREA OF SQUARE: " WS-AREA.
           ...

Output -

LENGTH OF WS-AREA VARIABLE: 000000004 
AREA OF SQUARE: 000100