Compare floats in php

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

    It would be better to use native PHP comparison:

    bccomp($a, $b, 3)
    // Third parameter - the optional scale parameter
    // is used to set the number of digits after the decimal place
    // which will be used in the comparison. 
    

    Returns 0 if the two operands are equal, 1 if the left_operand is larger than the right_operand, -1 otherwise.

提交回复
热议问题