0
Good afternoon guys! I’m facing little problem here with percentage calculation and I’m having trouble getting to the final goal.
I have to calculate the percentage difference of each recipient in the purchase, according to the total purchase. Where at the end the total sum of the percentage of each receiver has to hit 100%.
Let’s try to calculate:
First I have these receivers, 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 purchase, in which 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 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 receiver, taking out its percentage relative to the purchase and added in the set of eachPercents, also converting from cents to decimal and rounding the percentage.
But as you can see, the percentages being returned are incorrect.
Where I am wrong. I thank you already. Hugs!
Perfect!! Thank you!
– Felipe Mathais