Search code examples
phparray-sum

array_sum numbers with different comma not equal to zero but long number


if(array_sum($request->amount) <> 0)
{
    session()->flash('sum_error','sum_error');
    return back();
}
else
    return array_sum($request->amount);

everything working fine with numbers like this

1
2
2
3
5
7
12
36

but when numbers in $request->amount be like this

278.75
35.96
-203
-13.92
-97.79

i have long numbers

-2.8421709430404E-14

how could i let array_sum give me zero result on this values thanks


Solution

  • Use sprintf to convert exponential formats to your desired ones.

    $sum = array_sum($request->amount);
    
    $sum = sprintf('%f', $sum);
    
    // or (if you want to limit the number of fractional digits to lets say 6
    $sum = sprintf('%.6f', $sum);
    
    // or use number_format function
    $sum = number_format($sum,5);
    
    if($sum <> 0)
    {
        session()->flash('sum_error','sum_error');
        return back();
    }
    else
        return $sum;