SHARE
TWEET

Untitled

a guest Jan 20th, 2019 64 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function percent($num_amount, $num_total) {
  2. $count1 = $num_amount / $num_total;
  3. $count2 = $count1 * 100;
  4. $count = number_format($count2, 0);
  5. echo $count;
  6. }
  7.    
  8. 1134
  9. 5391
  10. 2374
  11. 2887
  12.    
  13. 1134 / 11786 = 0.09621....
  14. 5391 / 11786 = 0.45740....
  15. 2374 / 11786 = 0.20142....
  16. 2887 / 11786 = 0.24495....
  17.    
  18. 0.09621.... becomes 0.10
  19.    
  20. function percent(array $numbers)
  21. {
  22.     $result = array();
  23.     $total = array_sum($numbers);
  24.  
  25.     foreach($numbers as $key => $number){
  26.         $result[$key] = round(($number/$total) * 100, 2);
  27.     }
  28.  
  29.     $sum = array_sum($result);//This is 100.02 with my example array.
  30.  
  31.     if(100 !== $sum){
  32.         $maxKeys = array_keys($result, max($result));
  33.         $result[$maxKeys[0]] = 100 - ($sum - max($result));
  34.     }
  35.     return $result;
  36. }
  37.  
  38.  
  39. $numbers = array(10.2, 22.36, 50.10, 27.9, 95.67, 3.71, 9.733, 4.6, 33.33, 33.33);
  40. $percentages = percent($numbers);
  41. var_dump($percentages);
  42. var_dump(array_sum($percentages));
  43.    
  44. array (size=10)
  45.   0 => float 3.51
  46.   1 => float 7.69
  47.   2 => float 17.22
  48.   3 => float 9.59
  49.   4 => float 32.86
  50.   5 => float 1.28
  51.   6 => float 3.35
  52.   7 => float 1.58
  53.   8 => float 11.46
  54.   9 => float 11.46
  55. float 100
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top