How do json_encode float values ​​in PHP 7.1.1?

PHP seems to have a bug in how 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 am not a server administrator, so without going into php.ini and changing serialize_precisionto -1, is there anything I can do in my code to protect against this when I cannot be sure that it works in the environment Where has this setting been changed?

EDIT: I'm sure some comments will be related to a general discussion of why there is floating point uncertainty. I know it. My question here is specifically about best practice for working with it in PHP and whether there is a way to protect it against it. Of course, there is a better way than sending floats as strings.

+4
source share
1 answer

You must configure the precision and 'serialize_precision' parameters .

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}"
+6
source

Source: https://habr.com/ru/post/1676730/


All Articles