Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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...!?

like image 239
bestprogrammerintheworld Avatar asked Oct 24 '25 14:10

bestprogrammerintheworld


2 Answers

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, ....))

like image 146
Karoly Horvath Avatar answered Oct 27 '25 03:10

Karoly Horvath


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"]);
like image 21
Anthony Avatar answered Oct 27 '25 04:10

Anthony



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!