Attempted to divide by zero Error ??

# Thread: Attempted to divide by zero Error ??

1. Senior Member
Join Date
Dec 1969
Posts
204

## Attempted to divide by zero Error ??

I created a grid control with 15 results per page. This worked initially, but now I keep getting this error: <BR>Attempted to Divide by Zero. Exception Details: System.DivideByZeroException: Attempted to divide by zero.<BR><BR>Anyone know why?<BR><BR>int resultsPerPage = 15; <BR>decimal pages = faqList.Count/15m; //m shows decimal <BR> <BR>if (pages % (Convert.ToInt32(pages)) == 0) <BR>totalPages = Convert.ToInt32(pages);<BR>else<BR>totalPages = Convert.ToInt32(pages) + 1;

2. Senior Member
Join Date
Dec 1969
Posts
204

## Also tried to Round Up, but it won't compile

totalPages = Convert.ToInt32(Math.Ceiling(1.4));<BR><BR>The first one compiled, but if I include my variable, a decimal, it says:<BR><BR>Argument cannot convert from decimal to double<BR><BR>totalPages = Convert.ToInt32(Math.Round(pages));<BR>

3. Senior Member
Join Date
Dec 1969
Posts
204

## Convert Decimal to Double

totalPages = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(page s)));

4. Senior Member
Join Date
Dec 1969
Posts
96,118

## As for the REASON for the error...

When you use the modulo operator (%) you are *really* doing a division (and then getting just the remainder from that division). So if the value of<BR> Convert.ToInt32(pages)<BR>is indeed zero, then of course you get a divide by zero error.<BR><BR>But see the other suggestions. MUCH more efficient than doing what you were trying.<BR><BR>Personally, I don&#039;t understand why you ever used any decimal values in the first place. Decimal has to be done all in software, as the x86 CPUs don&#039;t support it. Use double for operations like this.<BR><BR><BR>

5. Senior Member
Join Date
Dec 1969
Posts
96,118

## Yes, but better...

...would be to have created pages as double in the first place. Decimal should be reserved exclusively for things like monetary calculations. And even then only when necessary. It&#039;s at least a couple of orders of magnitude slower than double. <BR><BR>

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•