1. 文章
  2. 文章详情

php 7.1版本json_encode 函数浮点类型数据精度不正确

项目用的 php 7.1 版本,在开发过程中发现 浮点类型 数据经过 json_encode 之后会出现精度问题

'price' => 0.1 转成json为 "price":0.10000000000000001

解决方法:

修改php.ini:调整 php.ini 中 serialize_precision (序列化精度) 的大小来解决

将这个值改为 小于 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 = 17

修改数据类型:将 float 转为 string 类型

'price' => (string)0.1

发表评论

登录后才能评论

评论列表(0条)