Fog Creek Software
Discussion Board




Crystal Reports - Division by Zero

Has anyone succesfully tested for zero before diving a number in Crystal reports?  I have this:

whileprintingrecords;
numbervar x;
iif(x <> 0, totext(currentfieldvalue/x), totext(currentfieldvalue))

I get a division by zero error, because Crystal evaluates the piece of code in the True part, even though it should only execute when x does not equal zero. 

Is there some other way I should check for x to be zero before I try to divide by it?

nathan
Monday, July 19, 2004

Change it to a normal if

whileprintingrecords;
numbervar x;

if x <> 0
    totext(currentfieldvalue/x)
else
    totext(currentfieldvalue)

DJ
Monday, July 19, 2004

Thank you!

nathan
Monday, July 19, 2004

Not a Crystal Reports user, so forgive me if this doesn't work/make sense, but you should be able to do something like this:

The general solution is to replace the 'if_true' part of the iif with an expression that is meaningless but valid if x=0, but an expression that still evaluates to currentfieldvalue/x if x<>0.  In this specific example, you can do one better:

totext(currentfieldvalue/iif(x=0, 1, x))

With this form, you don't even need the higher-level iif, unless you think it makes your intentions more clear.

schmoe
Monday, July 19, 2004

BTW

The iif() function works that way by design in Crystal, VB and VBA.

DJ
Monday, July 19, 2004

If you think about it: The iif() function is a FUNCTION and not a STATEMENT.

Just like any other function call, arguments that are expressions are first evaluated and then passed to the iif() function. So you shouldn't pass any expression that might have side effects you don't want.

Daren Thomas
Tuesday, July 20, 2004

*  Recent Topics

*  Fog Creek Home