Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Warning: Massive error in json_encode()

Tags:

json

ajax

php

<?php  
$int = 1968401665333658496;  
echo json_encode( array("$int",$int) );  
?>  

Recieved in browser: [ "1968401665333658496" , 1968401665333658600 ]

It "rounds off" my integer?

Btw : PHP_INT_MAX = 9223372036854775807 ~ PHP Version 5.3.2-1ubuntu4.7
No problems with these huge integers anywhere (PHP, MySQL or Javascript)
- until json_encode() screws it up (silently btw..)

like image 541
T4NK3R Avatar asked Apr 04 '11 16:04

T4NK3R


2 Answers

It's not just a JSON issue. If you put

alert(1968401665333658496);

in firebug console you get 1968401665333658600

You're probably hitting the JS max value.

There's a discussion on that here : What is JavaScript's highest integer value that a Number can go to without losing precision?

like image 187
JohnP Avatar answered Sep 28 '22 14:09

JohnP


Javascript has no concept of integers, according to the standard all numbers are IEEE doubles, which means they have 52 bits of mantissa. this leads to a practical maximum "integer" value of 2^53 before any loss of precision.

I am not sure how you didn't have problems with numbers this large in JS alone - if you didn't your JS implementation is not standards compliant.

like image 24
tobyodavies Avatar answered Sep 28 '22 15:09

tobyodavies