PHP-使用json_decode浮点数错误的精度 [英] PHP - float numbers wrong precision with json_decode
问题描述
当尝试使用PHP 7.0.21中的json_decode函数解码JSON时遇到问题.我可以使用以下几行代码来复制此问题:
I have an issue when trying to decode JSON with the json_decode function in PHP 7.0.21. I am able to replicate this problem with these lines of code:
代码:
<?php
$inputJSON = '{"value":0.00000883}';
$outputJSON = json_decode($inputJSON);
print_r($outputJSON);
输出:
stdClass Object
(
[value] => 8.83E-6
)
我还尝试使用ini_set('precision', 8);
更改精度,但不会更改输出.
I also tried changing the precision with ini_set('precision', 8);
which doesn't change the output.
我在网上发现的唯一修复是regex替换,它将数字更改为字符串,但这是一个不错的解决方案.我不想将我所有的浮点数都更改为字符串.
The only fixes I found online were regex replaces which changed the number into a string but that's a hack and a good solution. I don't want to change ALL my float numbers to strings.
为什么会发生这种情况,以及如何正确解决此问题而又不增加使用number_format
之类的大量开销.解析只是在json_decode中被破坏了吗?
Why is this happening and how can I fix this properly without adding a lot of overhead like using number_format
. Is the parsing simply broken in json_decode?
推荐答案
You can use number_format to remove the e-6
so you can store correctly in your database;
<?php
$inputJSON = '{"value":0.00000883}';
$outputJSON = json_decode($inputJSON);
$formatted = number_format($outputJSON->value,8);
print_r($formatted);
输出:0.00000883
outputs: 0.00000883
尽管如此,我很确定MySQL应该将8.83E-6
作为输入处理.
Although, I'm pretty sure MySQL should handle 8.83E-6
as an input.
这篇关于PHP-使用json_decode浮点数错误的精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!