How to extract the percentage from the array

Viewed 79

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>';
}
4 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).

Rounding!

Take the number 500.36;

500.36 / 1200.77 * 100: 41,669928463

Since you're using intval those deciamals are lost, remove intval to keep the decimals, then you'll reach 100 total.

Consider an extra variable to check this;

<?php
$sum = array(500.36,200.32,100.09,400);
$total =  array_sum($sum);
$test = 0;
foreach($sum as $val){
    $st = $val / $total * 100;
    echo $st.'<br>';
    $test += $st;
}
echo $test;
41.66992846257
16.682628646618
8.3354847306312
33.311958160181
100

Try it online!

you are using intval(). you should use round() with the precision of 2. you are skipping fractions by converting answer to integer. PHP is using floor method so your answer is losing fractions. here is the code

$sum = array(500.36,200.32,100.09,400);
$total =  array_sum($sum);
foreach($sum as $val){
    $st = round($val / $total * 100, 2 );
    echo $st.'<br>';
}

If you make an intval to the result you cut the last values.

Without intval you can see the problem.

41.66992846257
16.682628646618
8.3354847306312
33.311958160181

So work with that numbers or round it on 2 decimal numbers.

$st = number_format($val / $total * 100, 2, '.', '');

something like this.

Related