FAQ: Why does the “Attempted to divide by zero” error still happen?
Symptom
I have 2 decimal data fields (Field1 and Field2) in a dataset, and use the expression with IIf function below to calculate the quotient. If the Field1 is not zero, the divide expression within the true part will be executed. Otherwise, just 0 will be returned.
=IIf(Fields!Field1.Value<>0, Fields!Field2.Value/Fields!Field1.Value, 0)
However, why I am still getting "#Error" when Field1 is zero?
The error message is as follows:
[rsRuntimeErrorInExpression] The Value expression for the textrun 'Textbox6.Paragraphs[0].TextRuns[0].TextRuns[0]' contains an error:
Attempted to divide by zero
Resolution
The cause of this error is that the IIf function always evaluates both the true part and the false part, even though it returns only one of them. This means both the true part and the false part need to be evaluated.
In order to resolve this issue, you need to use a nested IIf function to avoid the zero-divisor in any rate.
=IIf(Fields!Field1.Value=0, 0, Fields!Field 2.Value/IIf(Fields! Field 1.Value=0, 1, Fields! Field 1.Value))
After that, you will get the correct result whether Field1 is 0 or not.
Workaround
You can also use custom code to prevent errors caused by dividing by zero.
Select click Report Properties on the Report menu. Click the Code tab and enter the following code in the Custom Code box:
Function Divide(Numerator as Decimal, Denominator as Decimal)
If Denominator = 0 Then
Return 0
Else
Return Numerator/Denominator
End If
End Function
After that, set the expression to be:
=Code.Divide(Fields!Field2.Value, Fields!Field1.value)
More Information
IIf Function:
https://msdn.microsoft.com/en-us/library/27ydhh0d(v=VS.90).aspx
Applies to
Reporting Services 2005
Reporting Services 2008
Reporting Services 2008 R2
Comments
Anonymous
October 10, 2013
Much needed article to avoid confusion with "IIF" , Thanks !!!Anonymous
August 10, 2015
Hello Sir I am using below function in my dashboard. In the Gauge panel facing this issue below is the expression . Please let me know the work around (IIf(RUNNINGVALUE(Fields!KPITitle.Value,CountDistinct,Nothing) MOD 2, "#D0D8E8","#E9EDF4"))Anonymous
August 13, 2015
It would be better if this behaved as expected.