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.
The json_encode() function is used to encode a value to JSON format.
Parsing JSON data in PHP: There are built-in functions in PHP for both encoding and decoding JSON data. These functions are json_encode() and json_decode(). These functions works only with UTF-8 encoded string. Decoding JSON data in PHP: It is very easy to decode JSON data in PHP.
The json_encode() function can return a string containing the JSON representation of supplied value. The encoding is affected by supplied options, and additionally, the encoding of float values depends on the value of serialize_precision.
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}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With