Search code examples
phpbcmath

Why is Bcmath returning innacurate results


Im having trouble getting bcmath to work with bitcoin based fractions on my server php 7.1 , ubuntu 18. Look at the following Code

bcscale(8);
$x1 = bcsub(0.04217 ,0.00007, 8);
$x2 = 0.04217 - 0.00007 ;
dd($x1 , $x2);

Result

"0.04217000"
0.0421

As you can see bcmath get return the first operand with some zeros added to it??. Any Ideas?


Solution

  • The manual is a little subtile but, the parameters are supposed to be strings. If you make them strings it will work.

    bcscale(8);
    $x1 = bcsub('0.04217' ,'0.00007', 8);
    $x2 = 0.04217 - 0.00007 ;
    
    echo 'x1 = '. $x1 . PHP_EOL;
    echo 'x2 = '. $x2;
    

    RESULT

    x1 = 0.04210000
    x2 = 0.0421
    

    Also from the manual

    Caution Passing values of type float to a BCMath function which expects a string as operand may not have the desired effect due to the way PHP converts float values to string, namely that the string may be in exponential notation (what is not supported by BCMath), and that the decimal separator is locale dependend (while BCMath always expects a decimal point).

    As to the precision,

    bcscale(8);
    $x1 = bcsub('0.04217' ,'0.00007', 6);
    //                                ^
    $x2 = 0.04217 - 0.00007 ;
    
    echo 'x1 = '. $x1 . PHP_EOL;
    echo 'x2 = '. $x2;
    

    RESULT

    x1 = 0.042100
    x2 = 0.0421
    

    And

    bcscale(8);
    $x1 = bcsub('0.04217' ,'0.00007', 4);
    //                                ^
    $x2 = 0.04217 - 0.00007 ;
    
    echo 'x1 = '. $x1 . PHP_EOL;
    echo 'x2 = '. $x2;
    

    RESULT

    x1 = 0.0421
    x2 = 0.0421