Preventing the “division by zero” error

Friday 26 July 2019 @ 9:52 am

Crystal formulas can use 3 different divide operators:

  • Regular divide [ / ]
  • Integer divide [ \ ]
  • Percentage [ % ]

But all of these will fail if you follow the operators with a zero. The report will stop and Crystal will throw the error message “Division by Zero”.  The standard solution is to check and make sure the number you are dividing by is not zero before you do the calculation, something like this:

if {fieldA} = 0
then 0
else {fieldB} / {fieldA}

This way, whenever the bottom of the fraction (denominator) is a zero, the formula will print a zero and NOT try to do the calculation.

But even when customers use this formula pattern I still see the divide by zero error. Some users mistakenly check the top of the fraction (numerator) instead of the bottom (denominator).  Some do it correctly at first, but then change the denominator and forget to change the first line to match.  So I have developed the habit of using Local variables to make things easier. My normal pattern now looks like this:

Local Numbervar n:= {FieldA};//numerator
Local Numbervar d:= {FieldB}; //denominator
if d = 0 then 0 else n/d

This ensures that the value being checked is always the value on the bottom. Some other advantages of this method are:

1) If d is a subtotal or a long expression you only have to enter it in one place.
2) If you have to create a series of similar expressions, like for 12 different months, you can duplicate the first example and you only have to change the values at the top of the formula.

(For examples of my most popular formulas, please visit the FORMULAS page on my website.)






One Response to 'Preventing the “division by zero” error'

  1. MHurwood - July 28th, 2019 at 6:09 pm

    There is one time when “Division by Zero” is a good thing – when you *want* to generate an error!
    When debugging very big formulas, putting a deliberate division by zero in the the middle of the formula means that when you run the report (in the development environment) you get an error, and then the formula is opened up for you, but you get the added bonus of the window on the left displaying the values of all your current variables, which can be great in diagnosing a problem.


Leave a Reply

Recrystallize Pro