bestprogrammerintheworld
bestprogrammerintheworld

Reputation: 5520

How to add many values in a good way with bcmath?

If I want to add several values together with BCMath I could do like this:

$total_cost1 = bcadd($value1, $value2);
$total_cost2 = bcadd($value3, $value4);
$total_cost3 = bcadd($value5, $value6);
$total_cost4 = bcadd($value7, $value8);

$total_cost = 
    bcadd(bcadd($total1_cost, $total2_cost), 
    bcadd($total3_cost, $total4_cost));

but it makes it so unreadable and it would be easy to make mistakes. Please tell me there is a another way of solving this...!?

Upvotes: 4

Views: 1917

Answers (2)

Anthony
Anthony

Reputation: 1926

Following up on Karoly's answer, you might implement it something like this:

function bcsum(array $numbers) : string {
    $total = "0";
    foreach ($numbers as $number) {
        $total = bcadd($total, $number, 2);
    }
    return $total;
}

bcsum(["1", "0.3", "0.33333", "0.033333"]);

Upvotes: 1

Karoly Horvath
Karoly Horvath

Reputation: 96266

There's nothing wrong with that approach, just hide it.

You can write a generic function which takes an array of numbers and adds them in a loop.

Then you can simply: bcsum(array($value1, $value2, ....))

Upvotes: 6

Related Questions