title: Warning: Division By Zero - Calculating percentages
body: <p>Okay, before I start, I would like to point out that I know dividing by zero is not good. What I'd like to know is, what's the best way to avoid this.</p>
  
  <p>In my CMS, I'm trying to display the amount of registered users that have recently signed up. The first statistic I'm showing is 'Registered Users Today' and showing whether this value is up or down from yesterdays value, and to show it as a positive/negative percentage.</p>
  
  <p>Reading other questions here on SO, people suggest avoiding the calculation altogether if one of the values equals 0, but surely if there were 0 registered users yesterday, and 20 today, there is a definitive increase that I need to display - I can't just show nothing.</p>
  
  <p>I have created this query:</p>
  
  <pre><code>SELECT
  COUNT(CASE WHEN DATEDIFF(HOUR, CURDATE(), created) &lt;= 24 THEN user_id
  ELSE NULL END) AS 1day,
  COUNT(CASE WHEN DATEDIFF(HOUR, CURDATE(), created) &gt;= 25 AND DATEDIFF(HOUR, CURDATE(), created) &lt;= 48 THEN user_id
  ELSE NULL END) AS 1to2days,
  ... other cases ...
  FROM users
  </code></pre>
  
  <p>This function:</p>
  
  <pre><code>function diff_percent($a, $b) {
      $c = ($a &gt; $b) ? ($a-$b)/$a*-100 : ($b-$a)/$b*100; 
      return $c;
  }
  </code></pre>
  
  <p>And simply call it by:</p>
  
  <pre><code>echo diff_percent($row['1to2days'], $row['1day']);
  </code></pre>
  
  <p>I could quite easily convert the zero to null using SQL, or I could stop the calculation in the function if a zero is detected, but as I mentioned above, if there were 0 users yesterday, and 20 today, I have to show that there is a considerable rise in users in the last 24-hours. What is the best way to get around this? If <code>todays_users &gt; yesterdays_users</code> but <code>yesterdays_users == 0</code> do I just show 'Up By 100%'? My math is poor and I'm very confused - please help.</p>