在php中比较花车 [英] Compare floats in php

查看:104
本文介绍了在php中比较花车的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


$ b

  $ a = 0.17;我想比较PHP中的两个浮点数,例如: 
$ b = 1 - 0.83; /0.17
if($ a == $ b){
echo'a and b are same';
}
else {
echo'a and b are not same';



$ b $ p
$ b

在这段代码中,它返回 else即使 $ a 条件而不是 > $ b 是一样的。有没有什么特殊的方法来处理/比较PHP中的浮动?



如果是的话请帮我解决这个问题。
$ b $如果你这样做,他们应该 是一样的。但是请注意,浮点值的一个特点是,导致相同值的计算似乎不需要实际上是相同的。所以如果 $ a 是一个文字 .17 $ b 通过一个计算到达那里,它可以是,他们是不同的,虽然都显示相同的值。

通常,你永远不会比较像这样的平等的浮点值,您需要使用最小的可接受差异:

pre $ code if(abs(($ a- $ b)/ $ b)< 0.00001){
echosame;

$ / code>

类似的东西。


I want to compare two floats in PHP, like in this sample code:

$a = 0.17;
$b = 1 - 0.83; //0.17
if($a == $b ){
 echo 'a and b are same';
}
else {
 echo 'a and b are not same';
}

In this code it returns the result of the else condition instead of the if condition, even though $a and $b are same. Is there any special way to handle/compare floats in PHP?

If yes then please help me to solve this issue.

Or is there a problem with my server config?

解决方案

If you do it like this they should be the same. But note that a characteristic of floating-point values is that calculations which seem to result in the same value do not need to actually be identical. So if $a is a literal .17 and $b arrives there through a calculation it can well be that they are different, albeit both display the same value.

Usually you never compare floating-point values for equality like this, you need to use a smallest acceptable difference:

if (abs(($a-$b)/$b) < 0.00001) {
  echo "same";
}

Something like that.

这篇关于在php中比较花车的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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