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.
json_encodewill now respect this.0.830cannot be represented exactly as floating point. It is an approximation. PHP provides a better approximation (with a lot of decimal places). That's all. You can format the value as string usingnumber_format()and put the string in JSON. Or, better, you can let it be a floating point number and do the formatting just before you want to put the value on screen.