在后台php中,金額保留兩位小數。但是前端顯示精度丟失,出現了14位小數的奇怪現象。本來以為是前端js解析之后出現的問題。檢查之后發現json_encode()之后就出現了。
原始的值:
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類型來避免。關於原因,可以看下面兩個回答:
https://stackoverflow.com/questions/42981409/php7-1-json-encode-float-issue#comment73056244_42981409
https://stackoverflow.com/questions/3726721/php-floating-number-precision