0
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

Awar Pulldozer
  • 1,071
  • 6
  • 23
  • 40
  • 1
    that's floating point precision limitations. Do something like `abs(array_sum($request->amount)) < 1e-3` setting tolerance to 0.001 – Madhur Bhaiya Sep 30 '18 at 10:55

2 Answers2

1

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

Sourabh
  • 157
  • 2
  • 12
1

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;
shreyas d
  • 774
  • 1
  • 4
  • 16