bccomp


php128 apg

COMPARE two arbitrary precision numbers.





This function returns:

 0 if $num1 = $num2

or

 1 if $num1 > $num2

or

-1 if $num1 < $num2.



<?php

int bccomp 
string $num1
                     
string $num2
                         ?
int $scale null )


where,

$num1 The left operand as STRING

$num2 
The right operand as STRING

$scale 
The number of decimal places 
                                to be considered in the comparison

?>
 

$num1


The left operand treated as STRING.



$num2


The right operand treated as STRING.



$scale


The number of decimal places to be considered.

This is nullable as of PHP 8.0.XX.



  1 EXERCISE   

<?php

function compare01($val01a$val01b$scl01)
{
    if(
bccomp($val01a$val01b$scl01) == 0)
    {
        echo 
$val01a ' = ' $val01b 
                      
' [ ' $scl01 ' decimal places ]<br><br>';
    }
    elseif(
bccomp($val01a$val01b$scl01) == 1)
    {
        echo 
$val01a ' &gt; ' $val01b 
                      
' [ ' $scl01 ' decimal places ]<br><br>';
    }    
    elseif(
bccomp($val01a$val01b$scl01) == -1)
    {
        echo 
$val01a ' &lt; ' $val01b 
                       
' [ ' $scl01  ' decimal places ]<br><br>';
    }

}

compare01('2020''2020'3);

compare01('2021''2020'0);

compare01('2020'20210);

compare01(2020.8762020.8782);

compare01(2020.8762020.8783);

compare01(2020.8782020.878null);

?> 

  2 EXERCISE   

<?php

function compare02($val02a$val02b)
{
    if(
bccomp($val02a$val02b) == 0)
    {
        echo 
$val02a ' = ' $val02b '<br><br>';
    }
    elseif(
bccomp($val02a$val02b) == 1)
    {
        echo 
$val02a ' &gt; ' $val02b '<br><br>';
    }    
    elseif(
bccomp($val02a$val02b) == -1)
    {
        echo 
$val02a ' &lt; ' $val02b '<br><br>';
    }

}

bcscale(3);
compare02('2020''2020');


bcscale(0);
compare02('2021''2020');

compare02('2020'2021);

bcscale(2);
compare02(2020.8762020.878);

bcscale(3);
compare02(2020.8762020.878);

?>