Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Division By Zero

I'm using a method to calculate some scores. This is the following method:

public function getIntScore($name, $int){
    switch ($name) {
        case "bedrooms":
            $maxscore = 15;
            break;
        case "living_size":
            $maxscore = 10;
            break;
        case "property_size":
            $maxscore = 10;
            break;
        case "date_of_construction":
            $maxscore = 3;
            break;
    }
    $houseattribute = (int) $this->$name;
    $difference = abs($houseattribute - $int);
    if ($difference == 0) {
        return $maxscore;
    }
    $score = ($difference / $houseattribute) * $maxscore;
    return round($score);
}

However, this gives me a "Division by zero" error. I checked the values of the variables before calculating and none of them are zero.

var_dump($difference, $houseattribute, $maxscore) 

outputs:

int(2) int(3) int(15) 
like image 928
Sietse Avatar asked Aug 11 '26 21:08

Sietse


1 Answers

Make sure you test for empty values:

$houseattribute = (int) $this->$name;
if (empty($houseattribute)) {
   throw new Exception('House attribute is zero.');
}
like image 94
Pentium10 Avatar answered Aug 13 '26 11:08

Pentium10



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!