LeviZoesch
LeviZoesch

Reputation: 1621

Functions throwing Division by zero error

First and foremost, I have searched SO, and haven't had much luck with the other suggestions, or I don't understand due to the complexity of the OP's question.

I have two functions that are throwing Division By Zero warnings.

How would I solve this? I have tried validating the logic, with isset(), empty(), but seem to be still having it.

Can someone educate me on where I am going wrong?

I appreciate any and all help :)

function roundUpToAny($MaterialCountNeeded, $CoverageMinimum) {
    if ( !isset($MaterialCountNeeded) AND !isset($CoverageMinimum) ) {
        $ReturnedValue = 0;
    }
    if ($MaterialCountNeeded === 0 & $CoverageMinimum === 0 || $CoverageMinimum === 0) {
        $ReturnedValue = 0;
    }
    else {
    $ReturnedValue = (ceil($MaterialCountNeeded) % $CoverageMinimum === 0) ? ceil($MaterialCountNeeded) : round(($MaterialCountNeeded + $CoverageMinimum / 2) / $CoverageMinimum) * $CoverageMinimum;
    }
    return $ReturnedValue;
}


function SumQuantityNeeded($Count, $Coverage) {
    if ($Count > 0) {
        $OrderMaterialCount = roundUpToAny($Count, $Coverage);
        $MinimumUnitAmount = $OrderMaterialCount / $Coverage;
        return round($MinimumUnitAmount,$Coverage);
    } else {
        return $MinimumUnitAmount = 0;
    }
}

Errors kick from MinimumUnitAmount = $OrderMaterialCount / $Coverage; and $ReturnedValue = (ceil($MaterialCountNeeded) % $CoverageMinimum === 0) ? ceil($MaterialCountNeeded) : round(($MaterialCountNeeded + $CoverageMinimum / 2) / $CoverageMinimum) * $CoverageMinimum;

These functions are 'Helper' functions. Other functions utilize these, so I may be looking in the wrong bucket...

Upvotes: 0

Views: 247

Answers (1)

Scopey
Scopey

Reputation: 6319

In the first, it appears you just need to check the second parameter is not zero.

function roundUpToAny($MaterialCountNeeded, $CoverageMinimum) {
    if (is_numeric($CoverageMinimum) && $CoverageMinimum > 0) {
        return (ceil($MaterialCountNeeded) % $CoverageMinimum === 0) ? ceil($MaterialCountNeeded) : round(($MaterialCountNeeded + $CoverageMinimum / 2) / $CoverageMinimum) * $CoverageMinimum;
    }

    return 0;
}

In the second, you should be checking $Coverage and not $Count:

function SumQuantityNeeded($Count, $Coverage) {
    if ($Coverage > 0) {
        $OrderMaterialCount = roundUpToAny($Count, $Coverage);
        $MinimumUnitAmount = $OrderMaterialCount / $Coverage;
        return round($MinimumUnitAmount, $Coverage);
    }

    return 0;    
}

I also simplified the functions a little.

Upvotes: 1

Related Questions