[英]Comparing 2 Same Decimal Numbers But Gives Wrong Result
I have this if condition : 我有这个如果条件:
if ($dc_real_vol != $dc_sum_vol) {
echo '||+++ REAL VOL ' . $dc_real_vol . PHP_EOL;
echo '||+++ SUM VOL ' . $dc_sum_vol . PHP_EOL;
echo '||+++ THIS TRADE IS DAMAGE ' . PHP_EOL;
}
when I checked the output : 当我检查输出时:
||+++ REAL VOL 0.60533000
||+++ SUM VOL 0.60533
||+++ THIS TRADE IS DAMAGE
why PHP consider 0.60533000
as different with 0.60533
? 为什么PHP认为
0.60533000
与0.60533
不同? how to make this condition marked as true? 如何将此条件标记为“真”?
update : 更新:
I tried solution from Loek below, and I changed my code like this : 我在下面尝试了Loek的解决方案,并且这样更改了代码:
$dc_real_vol = (float) $dc_real_vol;
$dc_sum_vol = (float) $dc_sum_vol;
echo '||*** REAL VOL ' . $dc_real_vol . PHP_EOL;
echo '||*** SUM VOL ' . $dc_sum_vol . PHP_EOL;
if ($dc_real_vol !== $dc_sum_vol) {
var_dump($dc_real_vol);
var_dump($dc_sum_vol);
echo '||+++ THIS TRADE IS DAMAGE ' . PHP_EOL;
}
and here's the result : 结果如下:
||*** REAL VOL 0.60533
||*** SUM VOL 0.60533
float(0.60533)
float(0.60533)
||+++ THIS TRADE IS DAMAGE
why same number, same type but PHP still recognised as different thing? 为什么相同的数字,相同的类型但PHP仍然识别为不同的东西?
I can't really explain why PHP thinks the numbers are different, I just know that they in fact are different at byte level. 我真的无法解释为什么PHP认为数字不同,我只知道它们实际上在字节级别上是不同的。
The easiest way I can think of is to cast both numbers to a float and then just proceed as you normally would: https://3v4l.org/uQdAP 我能想到的最简单的方法是将两个数字都转换为浮点数,然后像往常一样继续进行操作: https : //3v4l.org/uQdAP
// Note we can even use !== instead of != now
if ((float) $dc_real_vol !== (float) $dc_sum_vol) {
echo '||+++ REAL VOL ' . $dc_real_vol . PHP_EOL;
echo '||+++ SUM VOL ' . $dc_sum_vol . PHP_EOL;
echo '||+++ THIS TRADE IS DAMAGE ' . PHP_EOL;
}
Format the numbers prior to comparison. 在比较之前格式化数字。
$dc_real_vol = number_format($dc_real_vol, 9);
$dc_sum_vol = number_format($dc_sum_vol, 9);
The actual reason your comparison isn't working is because you are most likely assigning these variables as strings
. 您的比较不起作用的实际原因是,您很可能将这些变量分配为
strings
。 PHP is weak typing. PHP是弱类型。 You can verify this by checking your variables prior to comparison with
var_dump
. 您可以通过在与
var_dump
比较之前检查变量来验证这一点。 Most likely PHP will report it has typed your variables as strings. PHP最有可能会报告它已将您的变量键入为字符串。 In which case, you should utilize
number_format
to properly compare them. 在这种情况下,您应该利用
number_format
进行正确比较。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.