php的json_encode()以後float類型丟失精度

在後臺php中,金額保留兩位小數。可是前端顯示精度丟失,出現了14位小數的奇怪現象。原本覺得是前端js解析以後出現的問題。檢查以後發現json_encode()以後就出現了。
原始的值:php

array(4) {
  ["data"]=>
  array(2) {
    ["saled"]=>
    object(Illuminate\Database\Eloquent\Collection)#1235 (1) {
      ["items":protected]=>
      array(0) {
      }
    }
    ["money"]=>
    array(3) {
      ["maket_total"]=>
      float(16794.48)
      ["voucher_total"]=>
      string(6) "744.00"
      ["favorable_total"]=>
      float(509.46)
    }
  }
  ["status"]=>
  int(0)
  ["msg"]=>
  string(12) "操做成功"
  ["total"]=>
  int(0)
}

json_encode()以後:string(170) "{"data":{"saled":[],"money":{"maket_total":16794.48,"voucher_total":"744.00","favorable_total":509.46000000000004}},"status":0,"msg":"\u64cd\u4f5c\u6210\u529f","total":0}"前端

這個字段favorable_total已經變成14位小數了。網上搜了一下,能夠經過轉化位string類型來避免。關於緣由,能夠看下面兩個回答:json

https://stackoverflow.com/questions/42981409/php7-1-json-encode-float-issue#comment73056244_42981409php7

https://stackoverflow.com/questions/3726721/php-floating-number-precisioncode

相關文章
相關標籤/搜索