# Thread: Division by 0 problem

1. ## Division by 0 problem

hello everyone,

I am generating a variable which is the result of the following, however code there are instances when there is no third party commission and the variable \$NEGOTIATIONSthirdpartypercentcommission should equal zero.

\$NEGOTIATIONSthirdpartypercentcommission = \$NEGOTIATIONSthirdpartyfinalcommission /\$NEGOTIATIONSthirdpartyoriginalcommission*100;

How do I fix this error

2. Validate the variables before you do the calculation?

3. ## division by zero

Maybe you could assign a default value that "approximates" infinity and then round the result down before you use it. eg.
20/40*100 = 50%
20/0*100 = not possible
20/10000*100 = .2%
floor(20/10000*100) = 0%
btw. Just my personal preference, but I enclose expressions in parentheses for clarity. It helps when expressions get more involved eg.
(20/40)*100 = 50%

4. I wrote this to try and validate the variable, but as you can see it's not quite right, as it simply assigns a value of 0 to \$NEGOTIATIONSthirdpartypercentcommission

<?

\$NEGOTIATIONSthirdpartyfinalcommission = 50;
\$NEGOTIATIONSthirdpartyoriginalcommission = 100;

if ( \$\$NEGOTIATIONSthirdpartyoriginalcommission == "0" )

{
\$NEGOTIATIONSthirdpartypercentcommission =\$NEGOTIATIONSthirdpartyfinalcommission / \$NEGOTIATIONSthirdpartyoriginalcommission*100;

}

\$NEGOTIATIONSthirdpartypercentcommission = 0;

echo "\$NEGOTIATIONSthirdpartypercentcommission";

?>

5. ## assign default

Try
PHP Code:
``` \$NEGOTIATIONSthirdpartyfinalcommission = 50; \$NEGOTIATIONSthirdpartyoriginalcommission = 0; \$NEGOTIATIONSthirdpartyoriginalcommission = (\$NEGOTIATIONSthirdpartyoriginalcommission != 0)?\$NEGOTIATIONSthirdpartyoriginalcommission:10000; \$NEGOTIATIONSthirdpartypercentcommission =floor(\$NEGOTIATIONSthirdpartyfinalcommission / \$NEGOTIATIONSthirdpartyoriginalcommission*100); echo \$NEGOTIATIONSthirdpartypercentcommission;  ```

6. Solved it.

switch (\$NEGOTIATIONSthirdpartyoriginalcommission){
case "0":
\$NEGOTIATIONSthirdpartypercentcommission= 0;
break;
default:
\$NEGOTIATIONSthirdpartypercentcommission=\$NEGOTIATIONSthirdpartyfinalcommission/\$NEGOTIATIONSthirdpartyoriginalcommission*100;

break;
}

7. It's a one-liner if you use the ternary operator:

PHP Code:
``` \$NEGOTIATIONSthirdpartypercentcommission = (\$NEGOTIATIONSthirdpartyoriginalcommission) ? \$NEGOTIATIONSthirdpartyfinalcommission / \$NEGOTIATIONSthirdpartyoriginalcommission * 100 : 0;  ```

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•