如何用bcmath以一种很好的方式添加许多值


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

如果我想在BCMath中添加几个值,我可以这样做:

$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));

,但它使它难以阅读,很容易出错。请告诉我还有别的办法解决这个问题…?

这种方法没有问题,只是隐藏它。

你可以编写一个泛型函数,它接受一个数字数组,并在循环中添加它们。

那么您可以简单地:bcsum(array($value1, $value2, ....))

根据Karoly的回答,您可以这样实现它:

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"]);