Welcome back! Having explored string types, signed integers, and unsigned decimals, we're now moving on to an important aspect — handling negative decimal values in COBOL. Understanding signed decimals will enable you to manage a wider range of data, including financial figures that often involve negative amounts.
In this lesson, you will learn how to define signed decimal variables and perform arithmetic operations with them. Specifically, we will cover:
Here’s a preview of what you’ll be doing:
cobol1IDENTIFICATION DIVISION. 2PROGRAM-ID. SignedDecimals. 3DATA DIVISION. 4WORKING-STORAGE SECTION. 501 Num1 PIC S9(6)V999. 601 Num2 PIC S9(6)V9 VALUE 345.6. 701 Result PIC S9(6)V99. 8PROCEDURE DIVISION. 9 MOVE -123.456 TO Num1. 10 DISPLAY 'Num1 = ' Num1. *> -123.456, digits at the end are truncated to have 3 decimal points. 11 DISPLAY 'Num2 = ' Num2. *> 345.6 12 13 SUBTRACT Num2 FROM Num1 GIVING Result. 14 DISPLAY 'Result = ' Result. *> -469.05, digits at the end are truncated to have 2 decimal points. 15 16 MULTIPLY Num1 BY Num2 GIVING Result. 17 DISPLAY 'Result = ' Result. *> -42666.39, digits at the end are truncated to have 2 decimal points. 18 19 DIVIDE Num2 BY Num1 GIVING Result. 20 DISPLAY 'Result = ' Result. *> -2.79, digits at the end are truncated to have 2 decimal points. 21 22 STOP RUN.
Note that the leading zeros in the outputs are skipped for simplicity.
Let's break down the code snippet to understand how signed decimals are defined and used in COBOL:
01 Num1 PIC S9(6)V999.
declares a signed decimal variable that can store up to six digits before and three digits after the decimal point, hence the notations S9(6)
and V999
. The S
indicates that the variable is signed, allowing it to hold negative values.01 Num2 PIC S9(6)V9 VALUE 345.6.
declares another signed decimal variable, initialized to 345.6
.Being able to work with signed decimals is critical for various real-world applications, such as banking, accounting, and scientific research. For example, balancing credits and debits in financial records requires precise handling of both positive and negative decimal values.
Mastering signed decimals ensures your programs can handle complex calculations accurately, which is essential for delivering reliable results in professional settings.
Exciting, right? Let's dive into the practice section and start coding together!