How to convert Decimal Values to Strings in COBOL

29,700

Solution 1

The fix sometimes involves REDEFINES as in:

01.
    05 Y PIC X(15).
    05 X REDEFINES Y PIC S9(7)V9(2).

Notice that X occupies less storage than Y so X can REDEFINE Y but not the other way round. Since both X and Y now occupy the same physical storage, the MOVE can be dropped as the following program and output illustrate:

   IDENTIFICATION DIVISION.
   PROGRAM-ID. EXAMPLE.
   DATA DIVISION.
   WORKING-STORAGE SECTION.              
   01  Y PIC X(15).
   01  X REDEFINES Y  PIC S9(7)V9(2).
   PROCEDURE DIVISION.
       MOVE -1234567.89 TO X
       DISPLAY 'X: >' X '< Y: >' Y '<'
       .

Output:

X: >12345678R< Y: >12345678R      <

As you can quickly see, the result is probably not what you were hoping for since Y does not contain a human readable formatted number (i.e. one with a leading sign and a decimal point).

So my advice to you is don't try bend COBOL into something that it is not. Use the language as it was intended to be used. What you probably need to do is something along the lines of:

   IDENTIFICATION DIVISION.             
   PROGRAM-ID. EXAMPLE.                 
   DATA DIVISION.                       
   WORKING-STORAGE SECTION.             
   01  Y PIC X(15).                     
   01  X PIC S9(7)V9(2).                
   01  T PIC -9(7).99.                  
   PROCEDURE DIVISION.                  
       MOVE -1234567.89 TO X            
       MOVE X TO T                      
       MOVE T TO Y                      
       DISPLAY 'X: >' X '< Y: >' Y '<'  
       GOBACK                           
       .                                

Which outputs:

X: >12345678R< Y: >-1234567.89    <

Yes, the above program uses an additional variable in the middle to convert numeric format to display format, but that is exactly how the language was designed. Long winded but very straight forward. At the end of the exercise variable Y contains something that is readable and makes sense to the normal human eye.

Solution 2

Depending on what you want Y to contain, no.

01  VARS.
    05  X PIC S9(7)V9(2).
    05  Y REDEFINES X PIC X(9).
    05  Z PIC -9(7).99.
    05  Q PIC X(11).

    MOVE X TO Z
    MOVE Z TO Q
    DISPLAY Y
    DISPLAY Q

Try it and see what gives you the answer you want.

Caveat, this was just freehand, I haven't tried compiling it.

Share:
29,700
mhshams
Author by

mhshams

Software Architect / Java Developer.

Updated on July 09, 2022

Comments

  • mhshams
    mhshams almost 2 years

    Given following code:

    VAR X  PIC S9(7)V9(2).
    VAR Y PIC X(15)
    

    Following code having compile error.

    MOVE  X TO Y.    * compile error.
    

    the error message is something like this "cannot move non-integer numbers to alphanumeric variable"

    is there any way to fix this issue without making use of another variables (e.g. display vars) ?