float php 下取,PHP-获取float变量内部值

迷南。 2022-08-30 11:14 202阅读 0赞

![Image 1][]

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

[Image 1]:

发表评论

表情:
评论列表 (有 0 条评论,202人围观)

还没有评论,来说两句吧...

相关阅读

    相关 float

    CSS 之 float我们几乎想不出其他任何使文字环绕图片的效果,除了使用float概念float 将元素放在包含这个元素容器的左边或右边,并允许文本或行内元素包围这个元...

    相关 float

    元素浮动的特性: 1、浮动的元素脱离了标准文档流,摆脱块级元素和行内元素的限制 2、浮动的元素存在相互贴靠的效果,当宽度不够的时候,会出现自动换行 3、浮动的元素虽然脱离

    相关 float

    1、浮动:使元素脱离标准普通流,移动到其父元素中相应位置 选择器{float:属性值;} left 元素向左浮动 right 元素