【问题标题】:Php laravel incorrectly formatted decimal value in a array [duplicate]Php laravel 数组中的十进制值格式不正确[重复]
【发布时间】:2021-07-15 03:42:07
【问题描述】:

我在 PHP 中进行计算,得到十进制值。到目前为止没有问题。当我将这些值放在一个数组中以使它们成为客户端时,一些值的格式非常糟糕。

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

总元素是造成问题的元素。如果总数是 7200.6,在客户端我得到 7200.599999999999。 当我记录数组时

[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',
)  

但是,当我在添加到表格之前显示总数时,它会显示 7200.6

这个问题从何而来?

提前感谢您的帮助

【问题讨论】:

  • 使用带有所需小数位数的舍入函数。
  • 这是关于Floating point precision的问题,很多程序语言都有这个问题。你可以阅读这个php.net/manual/en/language.types.float.php
  • 你可以使用number_format php函数

标签: php arrays laravel


【解决方案1】:
$res = [
    "amount" => $this->amount_cfa,
    "x_fee" => $this->x_fee,
    "part_fee" => $this->part_fee,
    "total" => round($total, 2),
    "dest" => $this->dest
];

【讨论】:

    猜你喜欢
    • 2022-01-02
    • 1970-01-01
    • 2016-04-27
    • 1970-01-01
    • 2017-09-13
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多