Why Not Floats
Part of the Data and Numbers section of Coddy's COBOL Programming journey. Lesson 19 of 23.
Most languages store fractions as binary floating point. COBOL has it too: COMP-1 and COMP-2 fields take no picture.
Binary cannot hold 0.1 or 0.7, only the nearest binary fraction. Adding the two gives a number a hair under 0.8:
01 A COMP-2 VALUE 0.1.
01 B COMP-2 VALUE 0.7.
01 C COMP-2.
COMPUTE C = A + B.
*> 0.7999999999999999Stored in a money field, the cut takes a whole cent:
01 CASH PIC 9V99.
COMPUTE CASH = A + B. *> 079A field with a picture stores decimal digits, so 0.10 plus 0.70 is 0.80 every time. That is why money in COBOL stays in PIC 9 fields, packed or not, and never in COMP-1 or COMP-2.
Challenge
EasyThe program turns a price into cents, but PRICE is a COMP-2, so 4.35 prints Cents: 00434. Declare PRICE as a decimal field with a picture, so it prints Cents: 00435.
Try it yourself
IDENTIFICATION DIVISION.
PROGRAM-ID. TOCENTS.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 PRICE COMP-2 VALUE 4.35.
01 CENTS PIC 9(5).
PROCEDURE DIVISION.
COMPUTE CENTS = PRICE * 100.
DISPLAY "Cents: " CENTS.
STOP RUN.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.