在PHP7的环境下使用json_encode()函数对数组进行编码的时候,发现浮点数溢出了。
<?php
echo json_encode(526.82); //输出 326.81999999999999
这个是由于php.ini的一个配置项引起的,参数名为serialize_precision
部分版本默认值为17,也有部分版本默认值为-1
如果配置项值为17就有可能遇到这个问题
; 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 = -1
想重现问题,值改为17就可以。
网络上部分记录建议改成16,但是我试了不行,所以还是使用默认值,改为-1