Reputation: 23
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:
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);
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. 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
. Is the parsing simply broken in json_decode?
Upvotes: 1
Views: 2623
Reputation: 1716
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);
outputs: 0.00000883
Although, I'm pretty sure MySQL should handle 8.83E-6
as an input.
Upvotes: 3