Home » Php » json – How to json_encode float values in PHP 7.1.1?

json – How to json_encode float values in PHP 7.1.1?

Posted by: admin July 12, 2020 Leave a comment


PHP seems to have a bug in the way it handles decimal precision in json_encode.

It’s easy to see just by encoding a simple float:

echo json_encode(["testVal" => 0.830]);

// Prints out:

I’m not much of a server admin, so aside from going into the php.ini and changing serialize_precision to -1, is there anything I can do in my code to protect against this when I can’t be sure it’s running in an environment where that setting has been changed?

I’m sure some comments will want to link against general discussions of why floating point imprecision exists. I know that. My question here is specifically about the best practice for dealing with it in PHP, and whether there is a way to code defensively against it. Surely there is a better way than sending floats as strings.

How to&Answers:

You should configure ‘precision‘ and ‘serialize_precision’ params.

precision = 14
serialize_precision = -1

Test case:

php -r 'ini_set("precision", 14); ini_set("serialize_precision", -1); var_dump(json_encode(["testVal" => 0.830]));'
string(16) "{"testVal":0.83}"