Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract the percentage from the array

Tags:

php

How to extract the percentage from the array
The result is as follows: 41 - 16 - 8 - 33
Total is 98, not 100
How to make it = 100

$sum = array(500.36,200.32,100.09,400);
$total =  array_sum($sum);
foreach($sum as $val){
    $st = intval($val / $total * 100 );
    echo $st.'<br>';
}
like image 815
ayobqorban Avatar asked Apr 06 '26 01:04

ayobqorban


1 Answers

The reason is: precision :) With intval() you skip the decimals. so 41+16+8+33 is REALLY 98.

If you add them with 2 decimals: 41.66 + 16.68 + 8.33 + 33.31 = 99.98

If you do round() instead of intval() you'll round the values so it'll be more close statistically. you'll get: 42 + 17 + 8 + 33 = 100

BUT! if you want to make sure the sum is 100, than you should pick one number (I suggest the biggest one) to calculate that as: 100 - sum(the rest).

like image 167
TeeCee Avatar answered Apr 08 '26 15:04

TeeCee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!