0

I do a calculation in PHP which gives me decimal values. So far no problem. When I put these values in an array to make them client-side, some values are very badly formatted.

$res = [
    "amount" => $this->amount_cfa,
    "x_fee" => $this->x_fee,
    "part_fee" => $this->part_fee,
    "total" => $total,
    "dest" => $this->dest
];

Log::info($res);

return response($res);

The total element is the one that poses the problem. if the total is 7200.6, on the client side I get 7200.599999999999. When I log the array

[2021-07-15 04:08:28] local.INFO: array (
  'amount' => '7200.00',
  'x_fee' => 0.36,
  'part_fee' => 0.24,
  'total' => 7200.599999999999,
  'dest' => '67349555',
)  

However when I display the total before being added to the table it displays 7200.6

Where does this problem come from?

Thank you in advance for your help

matiaslauriti
  • 4,495
  • 4
  • 29
  • 37
  • 1
    Use a round function with the number of decimals you want. – Ravi Jul 15 '21 at 03:51
  • 1
    it's is about `Floating point precision` problem,many program language has the problem.you can read about this https://www.php.net/manual/en/language.types.float.php – nay Jul 15 '21 at 03:54
  • You may use `number_format` php function – A.A Noman Jul 15 '21 at 03:55

1 Answers1

0
$res = [
    "amount" => $this->amount_cfa,
    "x_fee" => $this->x_fee,
    "part_fee" => $this->part_fee,
    "total" => round($total, 2),
    "dest" => $this->dest
];
Stephan Vierkant
  • 8,894
  • 8
  • 53
  • 89