-1

I'm thinking about writing a simple function to handle all my division for my web application. The main reason is to catch division by 0 errors. I'm thinking I'll just return 0 when division by 0 is attempted.

Am I completely thinking wrong here?

The web application is very extensive and currently used by 5 different businesses. It records and processes over 10,000 different records every day. So saying stop dividing by zero is simply not a solution.

user2843198
  • 95
  • 1
  • 9
  • 2
    Last I check it is impossible to divide by zero to begin with. So I think what you need to do is error check your information better before performing your arithmetic. Wouldn't you rather inform your customers that a calculation cannot be done instead of just telling them `0` is the number? I think this is more of a business related decision, but if it where me, I would tell the customer about it as they may have put in the wrong infomation. – Crackertastic Oct 02 '14 at 14:22
  • Why are you trying to divide by 0 in the first place and what do you think the correct result should be? There is no general answer to your question. Dividing by 0 is not possible, period. "Suppressing the resulting error" *may* be the correct solution for your situation, or maybe it's not. Any general developer and/or mathematician would say that the correct solution is not to divide by 0 in the first place. – deceze Oct 02 '14 at 14:50
  • @deceze I agree with your statement, but I was looking for advice to suppress the error and still give the end user something. I know that division by 0 is not possible, I was just looking for advice and or solutions others have implemented. – user2843198 Oct 02 '14 at 15:52
  • And again, that's honestly an unanswerable question, because it depends entirely on *you* and your situation what you want to do instead of an impossible operation. We cannot tell you. – deceze Oct 02 '14 at 15:53

1 Answers1

0

Try something like this:

function division($dividend, $divisor) {
    if ($divisor == 0) {
        //change this return value to whatever fits your code 
        return 0;
    } else {
        return $dividend / $divisor;
    }
}

Usage:

echo division(4, 2);     // 2
echo division(9, (5-1)); // 2.25
echo division(1, 0);     // 0

You could also throw an Exception if the divisor equals zero or return false, for example, and treat the error in whatever way you need.