user2029763
user2029763

Reputation: 143

json_decode and E numbers in PHP

I have tried solutions given in other threads, but unfortunately not yet come to a solution.

The json that I am retrieving is:

{"foo": [
        {"coo": "2013-01-01 13:42:21",
            "moo": 0.00008200,
        }
    ]
}

I am using the following code to parse it:

$jsonString=preg_replace('/([^\\\])" *: *([0-9]{10,})(,|})/', '$1":"$2"$3', $jsonString);

$jsonString=json_decode($jsonString, true);

However, the value for moo is showing as: 8.02E-5

What can I do to rectify this?

Upvotes: 0

Views: 1629

Answers (2)

You could make use of sprintf()

<?php
$json='{"foo":
    [
    {   "coo": "2013-01-01 13:42:21",
        "moo": 0.00008200
    }
    ]
}';

$jsonString=json_decode($json, true);
echo sprintf('%.6f', $jsonString['foo'][0]['moo']);// "prints" 0.000082

Upvotes: 3

Jason Fingar
Jason Fingar

Reputation: 3368

PHP uses scientific notation when you exceed the floating point precision limit that can be set in the php config options.

Try adding:

ini_set('precision',20);

for example, to change your floating point precision limit to 20.

Upvotes: 4

Related Questions