Reputation: 2720
I met some trouble in php json decode number.
$json = '[{"num":123456789011121314},{"num":1516171819202122232425}]';
$number = json_decode($json);
foreach($number as $num){
echo $num->num.'<br />';
//echo (int)$num->num.'<br />';
}
this will get:
1.23456789011E+17
1.5161718192E+21
Also (int) do a wrong callback. And how to get the orignal number? Thanks.
I need
123456789011121314
1516171819202122232425
Upvotes: 2
Views: 1688
Reputation: 147
Since the json structure is not complicated, we can fix it with a simple regular expression. The idea is to enclose numbers in doublequotes.
$json = '[{"num":123456789011121314},{"num":1516171819202122232425}]';
$sanitized = preg_replace('/:(\w*\d+)/', ':"$1"', $json);
$number = json_decode($sanitized);
This should work fine for you as did for me.
The pattern matches to a colon followed by some optional whitespace followed by a number.
Upvotes: 1
Reputation: 24032
If you're using PHP 5.4 or later, you can do this:
$number = json_decode($json, true, 512, JSON_BIGINT_AS_STRING);
Which will represent those large numbers as strings instead of ints. If you have access to the code generating the json, you could also encode the numbers as strings.
Upvotes: 4
Reputation: 324840
Use a 128-bit system?
That second number is bigger than even a 64-bit machine can hold as an integer, thus it is being converted to float. Cue precision loss and exponent parts.
Another solution: use smaller numbers.
If you absolutely must have these numbers, look into APIs like BC-Math or GMP.
Upvotes: 0