Search code examples
cobolgnucobol

COBOL supress last number while summing two decimal numbers


According to the COBOL code below when I try to sum WS-NUM1 with WS-NUM2, COBOL seems to supress the last number. For example: variable WS-NUM1 and WS-NUM2 are 10.15, I get 20.20 as result but expected 20.30. What's wrong?

WS-NUM1 PIC 9(2)V99.
WS-NUM2 PIC 9(2)V99.
WS-RESULTADO PIC 9(2)V99.

DISPLAY "Enter the first number:"
ACCEPT WS-NUM1.
DISPLAY "Enter the second number:"
ACCEPT WS-NUM2.
COMPUTE WS-RESULTADO = WS-NUM1 + WS-NUM2.

Thanks in advance.


Solution

  • PIC 9(2)v99 defines a variable with an implied decimal place not a real one. You're trying to enter data containing a decimal point and it's not working because you have to strip out the '.' to get the numeric part of your data to properly fit in the 4 bytes that your working storage area occupies.

       PROGRAM-ID. ADD2.
    
       data division.
       working-storage section.
    
       01 ws-num-input pic x(5).
    
       01 WS-NUM1 PIC 9(2)V99 value 0.
       01 redefines ws-num1.
          05 ws-high-num  pic 99.
          05 ws-low-num   pic 99.
    
       01 WS-NUM2 PIC 9(2)V99 value 0.
       01 redefines ws-num2.
          05 ws-high-num2  pic 99.
          05 ws-low-num2   pic 99.
    
       01 WS-RESULTADO PIC 9(2)V99.
    
       PROCEDURE DIVISION.
       DISPLAY "Enter the first number:"
      *
       accept ws-num-input
       unstring ws-num-input delimited by '.'
           into ws-high-num, ws-low-num 
    
       DISPLAY "Enter the second number:"
       accept ws-num-input
       unstring ws-num-input delimited by '.'
           into ws-high-num2, ws-low-num2 
      *
       COMPUTE WS-RESULTADO = WS-NUM1 + WS-NUM2.
       DISPLAY WS-RESULTADO
       STOP RUN
       .
    

    This is just a simple demonstration. In a real world application you would have to insure much more robust edits to ensure that valid numeric data was entered.