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

380 Views Asked by At
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

2

There are 2 best solutions below

0
On BEST ANSWER

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;
1
On

You can cast your array sum to integer that will give you output as zero for exponential value

Try below solution:

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

I have simple cast to integer value