JSON Encoding of number problem

You can get quite surprising results if you try to json_encode something like json_encode($n[“number”]=3.53).

echo json_encode($n["number"]=3.53);
3.5299999999999998

Seems there is a bug in PHP, that parse floats with wrong precision.

Currently json_encode() uses EG(precision) which is set to 14.

The solution is to cast the number to string:

echo json_encode($n["number"]=(string) 3.53);
"3.53"

Another solution is to set the precision explicitly:

ini_set( 'serialize_precision', -1 );
echo json_encode($n["number"]=3.53);
3.53

Weird bug, that’s causing quite some headscratching.

You could also set it in php.ini:

serialize_precision = -1

Comments are closed.

Categories
Archives
Links