php, var_export fails with float [duplicate]

≡放荡痞女 提交于 2021-02-05 05:25:45

问题


very simple. Consider this code:

var_export (11.2);

this returns with

11.199999999999999

with Php 5.6

wtf?


回答1:


From the comments on the man page of php.net:

Looks like since version 5.4.22 var_export uses the serialize_precision ini setting, rather than the precision one used for normal output of floating-point numbers. As a consequence since version 5.4.22 for example var_export(1.1) will output 1.1000000000000001 (17 is default precision value) and not 1.1 as before.

Good to know. I too was not aware of this change.

serialize_precision

Available since PHP 4.3.2. Until PHP 5.3.5, the default value was 100.

So, we can get the behavior we were familiar with using: ini_set('serialize_precision', 100);

Warning

Be very careful when using ini_set(), as this may change behaviour of your code further down the line. A "safe" way would be to use something like this:

$storedValue = ini_get('serialize_precision');
ini_set('serialize_precision', 100);
// Your isolated code goes here e.g var_export($float);
ini_set('serialize_precision', $storedValue);

This ensures that changes further down/deeper in your code is not affected.

Generally, using ini_set() in your code should be considered dangerous, as it can have severe side effects. Refactoring your code to function without the ini_set() is usually a better choice.



来源:https://stackoverflow.com/questions/32149340/php-var-export-fails-with-float

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!