Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function percent($num_amount, $num_total) {
- $count1 = $num_amount / $num_total;
- $count2 = $count1 * 100;
- $count = number_format($count2, 0);
- echo $count;
- }
- 1134
- 5391
- 2374
- 2887
- 1134 / 11786 = 0.09621....
- 5391 / 11786 = 0.45740....
- 2374 / 11786 = 0.20142....
- 2887 / 11786 = 0.24495....
- 0.09621.... becomes 0.10
- function percent(array $numbers)
- {
- $result = array();
- $total = array_sum($numbers);
- foreach($numbers as $key => $number){
- $result[$key] = round(($number/$total) * 100, 2);
- }
- $sum = array_sum($result);//This is 100.02 with my example array.
- if(100 !== $sum){
- $maxKeys = array_keys($result, max($result));
- $result[$maxKeys[0]] = 100 - ($sum - max($result));
- }
- return $result;
- }
- $numbers = array(10.2, 22.36, 50.10, 27.9, 95.67, 3.71, 9.733, 4.6, 33.33, 33.33);
- $percentages = percent($numbers);
- var_dump($percentages);
- var_dump(array_sum($percentages));
- array (size=10)
- 0 => float 3.51
- 1 => float 7.69
- 2 => float 17.22
- 3 => float 9.59
- 4 => float 32.86
- 5 => float 1.28
- 6 => float 3.35
- 7 => float 1.58
- 8 => float 11.46
- 9 => float 11.46
- float 100
Add Comment
Please, Sign In to add comment