GoldenJoe
GoldenJoe

Reputation: 8002

How to json_encode float values in PHP 7.1.1?

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:
{"testVal":0.82999999999999996003197111349436454474925994873046875}

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?

EDIT: 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.

Upvotes: 14

Views: 10085

Answers (1)

Valery Viktorovsky
Valery Viktorovsky

Reputation: 6726

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}"

Upvotes: 12

Related Questions