Laravel5.5 JSON 响应出现浮点小数溢出问题
环境:php7.1+laravel5.5
现象描述:在进行接口输出,因为使用了JSON 响应
return response()->json()
出现了浮点数
10.629999999999997
的问题
1,查看了laravel
文档
json 方法会自动把 Content-Type 响应头信息设置为 application/json,并使用 PHP 函数 json_encode 将给定的数组转换为 JSON:
return response()->json([
'name' => 'Abigail',
'state' => 'CA'
]);
表示通过json_encode
将数组转为json
,所以问题出现在json_encode
上面
2,经过网上查询得知
该现象只出现在PHP 7.1+版本上
PHP RFC:更精确的浮点值处理
网上说可以通过调整 php.ini 中 serialize_precision (序列化精度) 的大小来解决这个问题。
默认值
serialize_precision = -1
; When floats & doubles are serialized store serialize_precision significant ; digits after the floating point. The default value ensures that when floats ; are decoded with unserialize, the data will remain the same. ; The value is also used for json_encode when encoding double values. ; If -1 is used, then dtoa mode 0 is used which automatically select the best ; precision. serialize_precision = 17
按照说明,将这个值改为 小于 17 的数字就解决了这个问题,最后一直往小调,我14的时候就没有问题了
这里参照了
本作品采用《CC 协议》,转载必须注明作者和本文链接