I made this to compare an unlimited size of numbers..
This could be useful for those without the BCMath extension.
It allows decimals, and option $Scale parameter. If $Scale isn't specified, then it'll automatically adjust to the correct number of decimals to compare.
<?php
function Comp($Num1,$Num2,$Scale=null) {
if(!preg_match("/^\+?(\d+)(\.\d+)?$/",$Num1,$Tmp1)||
!preg_match("/^\+?(\d+)(\.\d+)?$/",$Num2,$Tmp2)) return('0');
$Num1=ltrim($Tmp1[1],'0');
$Num2=ltrim($Tmp2[1],'0');
if(strlen($Num1)>strlen($Num2)) return(1);
else {
if(strlen($Num1)<strlen($Num2)) return(-1);
else {
$Dec1=isset($Tmp1[2])?rtrim(substr($Tmp1[2],1),'0'):'';
$Dec2=isset($Tmp2[2])?rtrim(substr($Tmp2[2],1),'0'):'';
if($Scale!=null) {
$Dec1=substr($Dec1,0,$Scale);
$Dec2=substr($Dec2,0,$Scale);
}
$DLen=max(strlen($Dec1),strlen($Dec2));
$Num1.=str_pad($Dec1,$DLen,'0');
$Num2.=str_pad($Dec2,$DLen,'0');
for($i=0;$i<strlen($Num1);$i++) {
if((int)$Num1{$i}>(int)$Num2{$i}) return(1);
else
if((int)$Num1{$i}<(int)$Num2{$i}) return(-1);
}
return(0);
}
}
}
$A="10.50002";
$B="10.50001";
printf(" Comp(%s,%s); // %s\r\n",$A,$B, Comp($A,$B));
printf("BCComp(%s,%s); // %s\r\n",$A,$B,BCComp($A,$B));
?>
I tried to make this behave like BCComp..
The only difference being mine will compare the decimals by default.. BCComp won't..
.. unless, of course, you specify the amount of decimals to include in the process.
Enjoy,
Nitrogen.