COMPUTE
The COBOL statement that calculates a formula and stores the result, such as COMPUTE TOTAL = PRICE * QUANTITY.
Also written ROUNDED, ON SIZE ERROR, ADD, SUBTRACT, MULTIPLY, DIVIDE
COMPUTE works out an arithmetic expression and stores the result: COMPUTE WS-INTEREST = WS-BALANCE * WS-RATE / 100. It uses the usual operators, + - * / and ** for powers, with brackets to control the order.
COBOL also has separate statements for single operations: ADD, SUBTRACT, MULTIPLY and DIVIDE, as in ADD WS-AMOUNT TO WS-TOTAL. Older programs use them a lot. COMPUTE is clearer for anything more complex.
Two options matter, especially with money. ROUNDED rounds the result to fit the receiving field instead of cutting off the extra decimal places. ON SIZE ERROR runs code when the result is too large for the receiving field. Without it, the high-order digits are lost and the program carries on with a wrong number, which can go unnoticed.
Arithmetic on fields that do not contain valid numbers fails with an S0C7 abend. Many programs check input fields with IF WS-AMOUNT IS NUMERIC before calculating with them.
Where can I learn this hands-on?
Right here, at ZedBank. You take a junior job at a simulated bank and learn each part of the work by doing it, with Zed beside you. There's nothing to install.
Start at ZedBankRelated
- Packed decimalA compact way of storing numbers, two digits per byte, used heavily for amounts in business records.
- PICTURE clauseThe COBOL declaration that says what kind of data a field holds and how long it is, written as PIC.
- MOVEThe COBOL statement that copies a value into a field, converting it to fit the receiving field's format.
- Zoned decimalThe default way COBOL stores numbers: one digit per byte, readable as text, with the sign hidden in the last byte.
- PROCEDURE DIVISIONThe part of a COBOL program that contains the actual logic, the statements that run.