Handle the divide-by-zero errors

Dividing by zero is considered an error by the Open Query File (OPNQRYF) command. This topic discusses how to handle the divide-by-zero error in case that you want a zero answer.

Record selection is normally done before field mapping errors occur. Therefore, a record can be omitted that would have caused a divide-by-zero error and in this case, processing by the OPNQRYF command would continue. If you want a zero answer, here is a solution that is practical for typical commercial data.

Assume that you want to divide A by B giving C (stated as A / B = C). Assume the following definitions where B can be zero.

Field Digits Dec
A 6 2
B 3 0
C 6 2
The following algorithm can be used:
(A * B) / %MAX((B * B) .nnnn1)

The %MAX function returns the maximum value of either B * B or a small value. The small value must have enough leading zeros so that it is less than any value calculated by B * B unless B is zero. In this example, B has zero decimal positions so .1 can be used. The number of leading zeros should be 2 times the number of decimals in B. For example, if B had 2 decimal positions, then .00001 should be used.

Specify the following MAPFLD definition:
MAPFLD((C '(A * B) / %MAX((B * B) .1)'))

The intent of the first multiplication is to produce a zero dividend if B is zero. This ensures a zero result when the division occurs. Dividing by zero does not occur if B is zero because the .1 value will be the value used as the divisor.