Reputation: 41
I want to calculate a rate value and i don't have the right result.
Everything works except the rate value
Can anybody help me to find the problem with my code.
This's my query :
$sql = "
SELECT
check_code.codegroup,
check.check_1,
check.check_2,
check.check_3,
COUNT(DISTINCT CASE WHEN status = 1 THEN check_product.product ELSE 0 END) as checkproduct
FROM check_code.code_group
LEFT JOIN check_product ON check_product.codegroup = check_code.codegroup
LEFT JOIN check ON check_product.codegroup = check.code_group
GROUP BY check_code.id_code_group
ORDER BY check_code.id_code_group DESC
";
<td>codegroup</td>
<td>checkproduct</td>
<td>check_1</td>
<td>check_2</td>
<td>check_3</td>
<td>Rate</td>
<?php
foreach ( $data as $query => $a ) :
//to calcule rate
$rate = ($a["check_1"] * 0.15) + ($a["check_2"] * 0.35) + ($a["check_3"] * 0.5) * 100 /$a["checkproduct"];
<td><? echo $a["codegroup"];?></td>
<td><? if($a["checkproduct"]==1){}else{echo $a["checkproduct"];}?></td>
<td><? echo $a["check_1"];?></td>
<td><? echo $a["check_2"];?></td>
<td><? echo $a["check_3"];?></td>
<td><? echo $rate;?></td>
Example :
This what my code return :
codegroup |checkproduct|check_1|check_2|check_3|rate
AL16bof05 94 1 1 1 1.031914893617
And this's what i want to return :
codegroup| checkproduct|check_1|check_2|check_3|rate
AL16bof05 94 1 1 1 1.06338297
Thanks for any help.
Upvotes: 0
Views: 34
Reputation: 1620
You are missing some brackets ()
to correclty interprete the Operator Precedence. This is basic Math and has nothing do to with 'coding'.
$rate = ($a["check_1"] * 0.15) + ($a["check_2"] * 0.35) + ($a["check_3"] * 0.5) * 100 /$a["checkproduct"];
This produces 1,031914894
Should become:
$rate = (($a["check_1"] * 0.15) + ($a["check_2"] * 0.35) + ($a["check_3"] * 0.5)) * 100 /$a["checkproduct"];
This produces 1,063829787
Please note the extra brackets
Upvotes: 1
Reputation: 7283
You missed a parenthesis, therefore the order of the operations is wrong, giving you the wrong result
$rate = ($a["check_1"] * 0.15) + ($a["check_2"] * 0.35) + ($a["check_3"] * 0.5)) * 100 /$a["checkproduct"];
^
This will basically do a 1 * 100/94
, meaning 1,063829787234043
Upvotes: 0
Reputation: 15656
This is basic math error. In details its about operators precedence.
Multiplication has precedence over (which means happens before) sum.
You have sum of 3 multiplication/division expressions:
$rate = ($a["check_1"] * 0.15)
+ ($a["check_2"] * 0.35)
+ ($a["check_3"] * 0.5) * 100 /$a["checkproduct"];
While you want to calulate sum first and then mupltiply it by 100 /$a["checkproduct"]
So you have to put brackets around sum:
$rate = ( ($a["check_1"] * 0.15) + ($a["check_2"] * 0.35) + ($a["check_3"] * 0.5) )
* 100 /$a["checkproduct"];
Upvotes: 2