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 andserialize()
/var_export()
uses PG(serialize_precision) which set to 17 be default to be more precise. Sincejson_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