This isn't a question as it is more of a be aware. I updated an application that uses json_encode()
to PHP7.1.1 and I was seeing an issue with floats being changed to sometimes extend out 17 digits. According to documentation, PHP 7.1.x started to use serialize_precision
instead of precision when encoding double values. I'm guessing this caused an example value of
472.185
to become
472.18500000000006
after that value went through json_encode()
. Since my discovery, I have reverted back to PHP 7.0.16 and I no longer have the issue with json_encode()
. I also tried to update to PHP 7.1.2 before reverting back to PHP 7.0.16.
The reasoning behind this question does stem from PHP - Floating Number Precision, however the end all reason for this is because of the change from precision to serialize_precision usage in json_encode()
.
If anyone does know of a solution to this problem, I'd be more than happy to listen in on the reasoning/fix.
Excerpt from multidimensional array (before):
[staticYaxisInfo] => Array
(
[17] => stdClass Object
(
[variable_id] => 17
[static] => 1
[min] => 0
[max] => 472.185
[locked_static] => 1
)
)
and after going through json_encode()
...
"staticYaxisInfo":
{
"17":
{
"variable_id": "17",
"static": "1",
"min": 0,
"max": 472.18500000000006,
"locked_static": "1"
}
},
ini_set('serialize_precision', 14); ini_set('precision', 14);
would probably make it serialize like it used to, however if you really rely on a specific precision on your floats you're doing something wrong. – Overweight1/3 != 0.333333333333333
either but we usually think them as being equal and we represent1/3
as0.33
or similar. The floating point numbers are approximations of the real numbers they represent. This happens both in real-life and in computers; only the set of numbers that cannot be represented exactly differs. Back to my original question: do you really need 14 decimal digits precision in your numbers? I guess not. Just format the number as string in PHP (usingnumber_format()
f.e.) and pass the string tojson_encode()
. – Savoieini_set('serialize_precision', 100); ini_set('precision', 100);
in PHP 5.X,would be better? – Light472.185
, in your sourcecode and in the JSON-serialized form. In memory, you had a binary representation that approximates this decimal representation. The serialization has been improved to better approximate what you had in memory. In my eyes, the expectations of the JS code are flawed, expecting a certain kind of representation is not reliable. – Nightclubini_set('serialize_precision', -1);
works for me. – Hug