Welcome back! Building on our recent lessons about handling strings and signed integers, we're now going to delve into the world of decimal numbers in COBOL. Understanding how to work with decimal numbers will expand your ability to handle more complex numerical data in your applications.
In this lesson, you will learn how to define and manipulate decimal numbers in COBOL. Specifically, we will cover:
To give you an initial idea, let's look at part of the code you'll create:
cobol1IDENTIFICATION DIVISION. 2PROGRAM-ID. UnsignedDecimals. 3DATA DIVISION. 4WORKING-STORAGE SECTION. 5 601 Num1 PIC 9(6)V999. 701 Num2 PIC 9(6)V9 VALUE 345.6. 801 Result PIC 9(6)V99. 9 10PROCEDURE DIVISION. 11 MOVE 123.4567 TO Num1. 12 DISPLAY 'Num1 = ' Num1. *> 123.456, digits at the end are truncated so that we have 3 digits after the decimal point. 13 DISPLAY 'Num2 = ' Num2. *> 345.6 14 15 ADD Num1 TO Num2 GIVING Result. 16 DISPLAY 'Result = ' Result. *> 469.05, digits at the end are truncated so that we have 2 digits after the decimal point. 17 18 STOP RUN.
Note that the leading zeros in the outputs are skipped for simplicity.
Let's dissect the key parts of this code snippet to understand how decimal numbers are defined in COBOL:
01 Num1 PIC 9(6)V999.
declares a decimal variable that can store up to six digits before the decimal point and three digits after it.01 Num2 PIC 9(6)V9 VALUE 345.6.
declares another decimal variable with 1 digit after the decimal point (hence, V9
) and initializes it with the value 345.6
.Decimal numbers are crucial in various real-world applications, such as financial calculations, scientific measurements, and any scenario requiring precise numerical data. For instance, managing a bank's transaction records involves accurately handling decimal values to avoid rounding errors that could lead to significant discrepancies in account balances.
Understanding how to work with decimal numbers in COBOL will ensure your programs can perform precise calculations and data processing, enhancing their robustness and reliability.
Exciting, right? Let's dive into the practice section and start coding together!