Search code examples
phpbcmath

Are PHP BC Math functions automatically converting integers and flaots to strings?


Are PHP BC Math functions automatically converting integers and flaots to strings? The example below works fine on PHP 7.4 on windows, but some people claim that BC Math only accepts strings as input. Why is bcdiv always returning 0?

For example:

print 'Result = '. bcdiv(40075036, 86164.098903691, 10);

Result = 465.1013184132

Solution

  • All operands, except as otherwise noted (i.e. precision), must be strings. BC Math conversion to string may not be relied upon. While some some conversion to strings takes place internally, such conversion is only useful for numbers, which when converted to sting using srtval() would produce a sting which is not in scientific notation. Also, all signed integers must be passed to BC Math as strings together with the sign, otherwise they may cause error, for example:

    This will produce a warning about "argument is not well-formed"
    $a = '10';
    $b = '0.00000000000000005551115111231258';
    print bcadd($a, -$b); 
    
    
    But this will work fine"
    $a = '10';
    $b = '-0.00000000000000005551115111231258';
    print bcadd($a, $b);   
    

    BC math is clumsy and cumbersome to work with and more complex calculations produce unreadable spaghtti code like this:

    bcadd('234', bcadd(bcmod(bcadd(bcdiv(bcsqrt(bcadd('4', bcpow($alpha, '2', 6))), '12'), $db), '11'), '234'))