How to fix divide by zero in asp.net razor

391 views Asked by At

I've got a group of query strings that run as follows:

var nq = db.QueryValue("select COALESCE(COUNT(*),0)from OPPORTUNITY where START_DATE = DATEDIFF(d,0,getdate())");  
var nrt = db.QueryValue("select COALESCE(COUNT(*),0)from OPPORTUNITY where START_DATE = DATEDIFF(d,0,getdate()) and OPPORTUNITY_STAGE = '-1'");  
var nrep = nrt / nq;

All it gives me is unhandled exeption: cannot divide by zero.

There is often going to be a zero in either or both of the first two query results. How do I get it to display NaN (not a number) instead of crashing?

I'm sure I've asked this before, but I couldn't seem to find what the answer was.

Thanks in advance.

2

There are 2 answers

0
John Woo On BEST ANSWER

how about adding IF condition?

var nq = db.QueryValue("select COALESCE(COUNT(*),0)from OPPORTUNITY where START_DATE = DATEDIFF(d,0,getdate())");

var nrep = 0;
if (nq != 0)
{
var nrt = db.QueryValue("select COALESCE(COUNT(*),0)from OPPORTUNITY where START_DATE = DATEDIFF(d,0,getdate()) and OPPORTUNITY_STAGE = '-1'");
nrep = nrt / nq;
}
5
Szymon On

You can simply replace

var nrep = nrt / nq;

with

Double nrep = Double.NaN;
if (nq != 0)
{
    nrep = nrt / nq;
}