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
fish man
  • 2,666
  • 21
  • 54
  • 94

3 Answers3

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.

Code Magician
  • 23,217
  • 7
  • 60
  • 77
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.

gabriel14
  • 137
  • 4
  • 9
  • 1
    Produce invalid JSON for {"test":":3432"}. – gimpe Aug 22 '12 at 13:31
  • @gimpe Indeed but I don't think that `":3432"` is a valid number. Is it? – gabriel14 Aug 24 '12 at 11:23
  • 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. – gimpe Sep 25 '12 at 15:41
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.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592