2

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
1

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Unfortunately that option is PHP 5.4+ though.
1

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.

3 Comments

Produce invalid JSON for {"test":":3432"}.
@gimpe Indeed but I don't think that ":3432" is a valid number. Is it?
No but it is a valid string. In fact I wanted to warn people to use this regular expression only in specific cases where there is only numbers and you cannot have user input looking like ":number". It almost worked for me :) thanks.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.