php json float,PHP7.1 json_encode()Float问题

这不是一个问题,因为它更多的是意识到.我更新了一个使用json_encode()到PHP7.1.1的应用程序,我看到一个问题,浮动被更改为有时延伸出17位数.根据文档,PHP 7.1.x在编码double值时开始使用serialize_precision而不是precision.我猜这导致了一个示例值

472.185

成为

472.18500000000006

在那个值经过json_encode()之后.自从我发现以来,我已经恢复到PHP 7.0.16并且我不再遇到json_encode()的问题.我还尝试在恢复到PHP 7.0.16之前更新到PHP 7.1.2.

这个问题背后的原因确实源于PHP – Floating Number Precision,但最终所有原因都是因为json_encode()中从精度到serialize_precision使用的变化.

如果有人知道这个问题的解决方案,我会非常乐意听取推理/修复.

摘自多维数组(之前):

[staticYaxisInfo] => Array

(

[17] => stdClass Object

(

[variable_id] => 17

[static] => 1

[min] => 0

[max] => 472.185

[locked_static] => 1

)

)

经过json_encode()之后……

"staticYaxisInfo":

{

"17":

{

"variable_id": "17",

"static": "1",

"min": 0,

"max": 472.18500000000006,

"locked_static": "1"

}

},

解决方法:

这让我疯了一会儿,直到我终于找到了this bug指向你的this RFC

Currently json_encode() uses EG(precision) which is set to 14. That means that 14 digits at most are used for displaying (printing) the number. IEEE 754 double supports higher precision and serialize()/var_export() uses PG(serialize_precision) which set to 17 be default to be more precise. Since json_encode() uses EG(precision), json_encode() removes lower digits of fraction parts and destroys original value even if PHP’s float could hold more precise float value.

而且(强调我的)

This RFC proposes to introduce a new setting EG(precision)=-1 and PG(serialize_precision)=-1 that uses zend_dtoa()’s mode 0 which uses better algorigthm for rounding float numbers (-1 is used to indicate 0 mode).

简而言之,有一种新方法可以使PHP 7.1 json_encode使用新的和改进的精确引擎.在php.ini中,您需要将serialize_precision更改为

serialize_precision = -1

您可以使用此命令行验证它是否有效

php -r '$price = ["price" => round("45.99", 2)]; echo json_encode($price);'

你应该得到

{"price":45.99}

标签:php,json,precision,php-7-1

来源: https://codeday.me/bug/20190925/1817438.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值