float php 下取_PHP-获取float变量内部值

在PHP中进行浮点数比较时,由于精度问题可能导致不准确的结果。可以通过设置'precision'配置来改变显示的精度。例如,使用`ini_set('precision', 18);`可以显示更多小数位,揭示浮点数之间的微小差异。当需要更精确的比较时,可以设置较小的delta值,如$delta=0.00000000000001,并考虑使用BCMath函数进行高精度计算。
摘要由CSDN通过智能技术生成

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.

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

$a = some_function();

$b = some_other_function();

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) returns 1.6215; 1.6215. but I know that they are not exactly equal because

var_dump($a === $b);

evaluates to false;

Why doesn't var_dump() print the internal value?

解决方案

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);

For example with with:

ini_set('precision', 18);

Your numbers may display something like:

float 1.62149999999999994

float 1.6214999999999995

So now the difference between them is clearer.

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

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

References / Sources

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值