简体   繁体   English

PHP-用json_decode浮点数错误的精度

[英]PHP - float numbers wrong precision with json_decode

I have an issue when trying to decode JSON with the json_decode function in PHP 7.0.21. 尝试使用PHP 7.0.21中的json_decode函数解码JSON时遇到问题。 I am able to replicate this problem with these lines of code: 我可以使用以下几行代码来复制此问题:

Code: 码:

<?php
$inputJSON = '{"value":0.00000883}';
$outputJSON = json_decode($inputJSON);
print_r($outputJSON);

Output: 输出:

stdClass Object
(
    [value] => 8.83E-6
)

I also tried changing the precision with ini_set('precision', 8); 我还尝试使用ini_set('precision', 8);更改精度ini_set('precision', 8); which doesn't change the output. 这不会改变输出。

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. 我在网上找到的唯一修复程序是regex替换,它将数字更改为字符串,但这是一个不错的解决方案。 I don't want to change ALL my float numbers to strings. 我不想将所有浮点数更改为字符串。

Why is this happening and how can I fix this properly without adding a lot of overhead like using number_format . 为什么会发生这种情况,以及如何正确解决此问题而又不增加使用number_format类的大量开销。 Is the parsing simply broken in json_decode? 解析只是在json_decode中被破坏了吗?

You can use number_format to remove the e-6 so you can store correctly in your database; 您可以使用number_format删除e-6以便可以将其正确存储在数据库中。

<?php

$inputJSON = '{"value":0.00000883}';
$outputJSON = json_decode($inputJSON);

$formatted = number_format($outputJSON->value,8);

print_r($formatted);

outputs: 0.00000883 输出:0.00000883

Although, I'm pretty sure MySQL should handle 8.83E-6 as an input. 虽然,我很确定MySQL应该将8.83E-6作为输入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM