php,var_export 失败,浮点数 [英] php, var_export fails with float

查看:23
本文介绍了php,var_export 失败,浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很简单.考虑以下代码:

very simple. Consider this code:

var_export (11.2);

这个返回

11.199999999999999

使用 PHP 5.6

wtf?

推荐答案

来自 php.net 手册页的评论:

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

看起来自 5.4.22 版以来 var_export 使用serialize_precision ini 设置,而不是使用的精度用于浮点数的正常输出.结果自从版本 5.4.22 例如 var_export(1.1) 将输出1.1000000000000001(17 是默认精度值)而不是之前的 1.1.

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

自 PHP 4.3.2 起可用.在 PHP 5.3.5 之前,默认值为 100.

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

所以,我们可以使用我们熟悉的行为:ini_set('serialize_precision', 100);

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

使用 ini_set() 时要非常小心,因为这可能会进一步改变代码的行为.一个安全的"方法是使用这样的东西:

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.

一般来说,在你的代码中使用 ini_set() 应该被认为是危险的,因为它可能会产生严重的副作用.重构您的代码以在没有 ini_set() 的情况下运行通常是更好的选择.

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.

这篇关于php,var_export 失败,浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆