Good afternoon everyone! I'm experiencing small problem here with percentage calculation and I'm having a hard time getting to the ultimate goal.
I have to calculate the percentage difference of each recipient in the purchase, according to the total purchase. Being that in the end the total sum of the percentage of each receiver has to hit 100%.
Let's try to calculate:
Firstly I have these recipients, each one already has its amount (they are in cents):
$recipients = [
[
"recipient_id" => "re_cisc9ja1e01u1gd6elgn8iudx",
"charge_processing_fee" => false,
"liable" => false,
"amount" => 3000.0
],
[
"recipient_id" => "re_cisc9jb9c01we2m6dueafa586",
"charge_processing_fee" => true,
"liable" => false,
"amount" => 1000.0,
],
[
"recipient_id" => "re_cisc9jbvz01wf2m6dogbkj6z1",
"charge_processing_fee" => false,
"liable" => true,
"amount" => 7870.0,
]
];
What I need is to take the percentage of each of them compared to the total of the purchase, in this case the total would be 118.70. So I did this:
$eachPercents = [];
$totalAmount = totalAmount($recipients);
foreach ($recipients as $recipient) {
$recipientAmount = cent_to_decimal($recipient['amount']);
$recipientPercent = round(($recipientAmount * $totalAmount) / 100);
array_push($eachPercents, $recipientPercent);
}
But the result that this generates is inconsistent:
array:3 [▼
0 => 36.0
1 => 12.0
2 => 93.0
]
36 + 12 + 93 = 141
The function totalAmount () returns me the total of the purchase according to what each recipient has, converted from cents to decimal. And the foreach passes each recipient, taking its percentage relative to the purchase and added in the set of eachPercents , also converting from cents to decimal and rounding the percentage.
However, as you can see, the percentages that are being returned are incorrect.
Where am I wrong. Thanks in advance. Hugs!