PHP-获取float变量内部值 [英] PHP - Getting a float variable internal value

查看:140
本文介绍了PHP-获取float变量内部值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在PHP中进行浮点比较时建立所需的增量. 我想仔细看一下我的变量以了解差异.

I am trying to establish the delta I need when doing float comparison in PHP. I want to take a closer look at my variables to see the difference.

我有2个计算变量$ a,$ b.

I have 2 computed variables, $a, $b.

$a = some_function();

$b = some_other_function();

如何查看PHP使用的确切数字?

How can I see the exact number which PHP uses?

我想将其与需要指定增量的公式进行比较:

I want to compare them with this formula, where I need to specify the delta:

$delta = 0.00001;
if (abs($a-$b) < $delta) {
  echo "identical";
}

var_dump($ a,$ b)返回1.6215; 1.6215.但我知道它们并不完全相等,因为

var_dump($a, $b) returns 1.6215; 1.6215. but I know that they are not exactly equal because

var_dump($a === $b);

计算为假;

为什么var_dump()不打印内部值?

推荐答案

在PHP中,浮点数的打印值取决于PHP配置精度".

In PHP, the printed values of floating point numbers are dependent on PHP configuration "precision".

您可以使用以下方法进行更改:

You can change that with:

ini_set('precision', YOUR_DESIRED_PRECISION_AS_INTEGER);

例如与:

ini_set('precision', 18);

您的电话号码可能显示类似以下内容:

Your numbers may display something like:

浮动1.62149999999999994

float 1.62149999999999994

浮动1.6214999999999995

float 1.6214999999999995

所以现在它们之间的区别更加明显了.

So now the difference between them is clearer.

所以您的增量可能是:$ delta = 0.00000000000001;这实际上取决于您要寻找的精度.

So your delta may be: $delta = 0.00000000000001; It really depends of the precision you are looking for.

如果您需要进行精确的数学计算,请查看 BC数学函数

If you need to do exact mathematical calculations, do have a look at the BC Math Functions.

参考/来源

PHP-浮点数

PHP-浮点数-用户贡献的注释-浮点上的小数净

键盘

这篇关于PHP-获取float变量内部值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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