Compare floats in php

后端 未结 16 1631
清歌不尽
清歌不尽 2020-11-22 00:47

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         


        
16条回答
  •  你的背包
    2020-11-22 01:29

    As said before, be very careful when doing floating point comparisons (whether equal-to, greater-than, or less-than) in PHP. However if you're only ever interested in a few significant digits, you can do something like:

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

    The use of rounding to 2 decimal places (or 3, or 4) will cause the expected result.

提交回复
热议问题