Compare floats in php

后端 未结 16 1635
清歌不尽
清歌不尽 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:17

    If you have a small, finite number of decimal points that will be acceptable, the following works nicely (albeit with slower performance than the epsilon solution):

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

提交回复
热议问题