0

I have a percentage calculation, but if no data is available, I get the following error message:

Division by zero

calculation

$ratio = ($postup*100)/($postup + $postdown);
slickness
  • 246
  • 7
  • 21

2 Answers2

2

Devision by zero is undefined.

If both $postup and $postdown are null (not set) you will get a division by zero i.e. null + null == 0.

Furthermore the same problem will occur if $postup * -1 == $postdown.

Since a division by zero is undefined you will need to add a fallback for this.

What this fallback would be is application specific but would look something like

$ratio = null;

if($postup + $postdown == 0) {
    $ratio = xxx;
} else {
    $ratio = ($postup*100)/($postup + $postdown);
}

Please also be aware that $postup * 100 will be equal to 0 if $postup == null

milo526
  • 5,012
  • 5
  • 41
  • 60
0

You can handle this, like the following to get rid of the error:

$ratio = 0;
$dividedBy = $postup + $postdown;

if($dividedBy != 0) {
    $ratio = ($postup * 100) / $dividedBy;
    echo $ratio;
} else {
    echo "Can not divide by zero!!";
}
Pranab Mitra
  • 401
  • 1
  • 4
  • 9