4

I have array like:

$array = ['id' => '76561198165327575'];

And I need it to work in JavaScript on client side. So I'm trying to encode it with JSON_NUMERIC_CHECK:

json_encode($array, JSON_NUMERIC_CHECK);

And getting result like:

{"id":7.6561198165328e+16}

But it should be:

{"id":76561198165327575}

What is wrong?

(Azure, Windows, 5.6)

1
  • 1
    you're probably on a 32bit PHP, which means you can't have anything larger than 2**32-1 for an int. Commented Sep 11, 2015 at 19:25

3 Answers 3

2

JSON_NUMERIC_CHECK basically tells the encoder "If it looks like a number, encode it as a number":

php > $x = '123456789012234567890';
php > echo json_encode($x, JSON_NUMERIC_CHECK);
1.2345678901223e+20
php > echo json_encode($x);
"123456789012234567890"

And since your number exceeds the representable range for an INT on your platform, you get a float instead.

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

5 Comments

I thought it's just stripping quots from all numeric values... Is there any way to fix it? (Except custom PHP on Azure)
not really. you could post-process the json string to remove the quotes, since it'll be just a plaintext string at that point, but then you risk mangling the json.
+ Answer is spot on. As an aside, you may want to look into JSON_BIGINT_AS_STRING.
@JasonMcCreary: good call, I keep forgetting that option's there, since it's not mentioned on the encode() page, only in the json constants one. But unfortunately, it still does the same thing - encodes the bigint as a string, not a raw number.
Indeed, it's the opposite of what the OP intended. It does preserve the precision though. Albeit as a string.
0

You are exceeding the bounds of integer on your 32-bit system. The documentation describes that when this occurs, the number is converted to a float.

If PHP encounters a number beyond the bounds of the integer type, it will be interpreted as a float instead. Also, an operation which results in a number beyond the bounds of the integer type will return a float instead.

Comments

0

If you encode in JSON objects with large numbers (greater than PHP_MAX_INT), you will always end up getting a floating point value. The only solution is to store them in the object/array as string (that you already) and not use JSON_NUMERIC_CHECK (but convert the string to a number on the client) or write your own encoding routine.

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.