In PHP, how do I ensure the sum of parts is 1?
$total = $a+$b+$c+$d;$percentA = ceil($a*100.0/$total);$percentB = ceil($b*100.0/$total);$percentC = ceil($c*100.0/$total);$percentD = ceil($d*100.0/$total);
The above code does not seem to ensure that the final sum is 100%
$percentD = 100-$percentA-$percentB-$percentC;
Is there any other method besides this?
Reply to discussion (solution)
Do not decimal places?
In addition, you don't have to turn around. do you need it?
$ PercentA = round ($ a x 100.0/$ total );
Do not decimal places?
In addition, you don't have to turn around. do you need it?
$ PercentA = round ($ a x 100.0/$ total );
Yes.
$a = array(1,2,3,3);$total = array_sum($a);array_walk($a, function(&$item, $key, $prefix) { $item = round($item*100/$prefix); }, $total);if($d = (100 - array_sum($a))) $a[rand(0, count($a)-1)] += $d;print_r($a);
$a = array(1,2,3,3);$total = array_sum($a);array_walk($a, function(&$item, $key, $prefix) { $item = round($item*100/$prefix); }, $total);if($d = (100 - array_sum($a))) $a[rand(0, count($a)-1)] += $d;print_r($a);
Thanks