Question

I have a simple division calculation after I've taken data from a MYSQL database

$calculation = round($number1/$number2,2);

Sometimes $number2 comes out the database as a 0 and I get a divide by zero error, is there a way to prevent the divide by zero warning and show a zero by default?

Was it helpful?

Solution

$gpg = $games == 0 ? 0 : round($goals / $games, 2);
$mpg = $goals == 0 ? 0 : round($minutes / $goals);

OTHER TIPS

Use a conditional:

$gpg = round($goals/($games ? $games : 1),2); // forces divisor to be 1 if $games == 0 
$mpg = round($minutes/($goals ? $goals : 1,2); // forces divisor to be 1 if $goals == 0

Note: this produces 0 values. You probably want to use if/else logic to say a stat is "not applicable" or not try to calculate these stats when you have 0 divisors, instead.

As for the formatting:

echo number_format($theNumber, 2);

Example:

echo number_format(1, 2); // outputs 1.00
if($goals != 0){
  $gpg = round($goals/$games,2);
  $mpg = round($minutes/$goals,2);
}

Your need a exeption or before detect the divison by Zero, check out:

<?php
/* Detect division by zero in PHP
 * 
 * More info:
 * 
 * - http://rosettacode.org/wiki/Detect_division_by_zero
 * -  http://www.php.net/trigger_error
 * -   http://php.net/error_get_last
 * 
 */ 
function tryDivision($x, $y) {
  $defaultVal = -1;
  @trigger_error('');
  $result = @($x / $y);
  if( $result === false) {
    /* Debug ERROR:
     * $e = error_get_last();
     * echo $e['message']; -> Division by zero
     * more information check: var_dump($e);
     */
    return $defaultVal;
  }
  return round($result, 2);
}

$gpg = tryDivision($goals, $games);
$mpg = tryDivision($minutes, $goals);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top