Search code examples
phpbcmath

Is there a consistent way to test for 0 (zero) when using BCMath?


Running the following, I would expect to receive N, Y, Y.

I understand why I'm not, because '0.00' != '0' for the second example, but is there a consistent way of testing for 0 without casting back to a float/double, and without dropping the === to a ==.

echo bcmul( '5.1', '2.234', 2 );
echo bcmul( '5.1', '2.234', 2 ) === '0' ? '  Y  ' : '  N  ';
echo "<br/>";

echo bcmul( '0.00', '000.00', 2 );
echo bcmul( '0.00', '000.00', 2 ) === '0' ? '  Y  ' : '  N  ';
echo "<br/>";

echo bcmul( '0', '0', 2 );
echo bcmul( '0', '0', 2 ) === '0' ? '  Y  ' : '  N  ';
echo "<br/>";

Notes

Why don't I want to drop the ===?

If I'm providing out functionality as part of a grander project, via a method such as get_total_cost(), I don't feel that it's intuitive to other developers to have to drop the strict comparison, when they are expecting the function to return a numeric value as a string.


Solution

  • A. Yes 0.00 !== 0 is valid because they are not the same type

    var_dump(0.00,0);
    

    Output

    float 0
    int 0
    

    B. 0 !== "0" is valid because they are not the same type

    var_dump(0,"0");
    

    Output

    int 0
    string '0' (length=1)
    

    C. Why don't I want to drop the ===

    var_dump("hello" == 0 );  true
    var_dump("hello" === 0 );  false
    

    Conclusion

    $a === $b TRUE if $a is equal to $b, and they are of the same type.

    I guess this is what you want

    echo (int) bcmul('0.00', '000.00', 2) === (int) '0' ? '  Y  ' : '  N  '; 
           ^                                    ^