简体   繁体   中英

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 ? how to make this condition marked as true?

update :

I tried solution from Loek below, and I changed my code like this :

$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?

I can't really explain why PHP thinks the numbers are different, I just know that they in fact are different at byte level.

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

// 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 . PHP is weak typing. You can verify this by checking your variables prior to comparison with var_dump . Most likely PHP will report it has typed your variables as strings. In which case, you should utilize number_format to properly compare them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM