Archive for November, 2019

JSON Encoding of number problem

Friday, November 8th, 2019

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);

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);

Another solution is to set the precision explicitly:

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

Weird bug, that’s causing quite some headscratching.

You could also set it in php.ini:

serialize_precision = -1

Your are browsing
the Archives of My Beloved PHP for November 2019.