Fix expression to avoid div/0?? (1 Viewer)

Sketchin

Registered User.
Local time
Yesterday, 23:51
Joined
Dec 20, 2011
Messages
575
I have this query expression that gives me a #NUM! error due to div/0.

PercentPaybackToDate: FormatPercent(((Sum(IIf([TransactionTypeID]=5,Nz([Amount]),0)))/(Sum(IIf([TransactionTypeID]=9,Nz([Amount]),0)))),0)

I can't for the life of me figure out how to test for a zero value in [Amount] to spit out a null or a zero if it = 0.
:banghead::banghead::banghead:
 

plog

Banishment Pending
Local time
Today, 01:51
Joined
May 11, 2011
Messages
11,646
The way you test for a zero value is with an If:

If ([Amount]=0, 0, {Amount to show if not 0 here})

With that said, I do not for the life of me want to spend time figuring out where to put it in your code. When you get that convoluted in your expressions, its time to move it to a function inside a module and then pass it the data it needs to do the logic.

I actually add a function to all my databases to do division and have it automatically catch errors in the inputs:

Code:
Function SafeDivision(in_Numerator, in_Denominator) AS Double
    ' does division and returns 0 if in_Denomintaor/in_Numerator is null or 0

ret = 0    ' return value, by default 0

'
' Logic here, to test for bad data, if good sets ret=in_Numerator/in_Denominator 
'

SafeDivision=ret

That way, I can just do the division with that function and not worry about invalid values.
 
Last edited:

The_Doc_Man

Immoderate Moderator
Staff member
Local time
Today, 01:51
Joined
Feb 28, 2001
Messages
27,179
First and foremost, I agree with plog that when you start getting THAT convoluted, you are probably making a big mistake somewhere in the design.

Second, however, the answer to your question about where to put your zero-divide check?

Code:
Iif( Nz([Amount],0) = 0, "0.00", FormatPercent(((Sum(IIf([TransactionTypeID]=5,Nz([Amount]),0)))/ (Sum(IIf([TransactionTypeID]=9,Nz([Amount]),0)))),0) 
)

In other words, bracket your entire expression and just don't bother to evaluate it when the divisor is zero. However, since there is more to your expression than I actually used, I actually prefer plog's comments as being more to the point. This situation screams for a dedicated computation function. Has to be a function since you need something that will return a value, of course.
 

Users who are viewing this thread

Top Bottom