I made this to add an unlimited size of numbers together..
This could be useful for those without the BCMath extension.
It allows decimals, and optional $Scale parameter. If $Scale isn't specified, then it'll automatically adjust to show the correct number of decimals.
<?php
function Add($Num1,$Num2,$Scale=null) {
if(!preg_match("/^\+?(\d+)(\.\d+)?$/",$Num1,$Tmp1)||
!preg_match("/^\+?(\d+)(\.\d+)?$/",$Num2,$Tmp2)) return('0');
$Output=array();
$Dec1=isset($Tmp1[2])?rtrim(substr($Tmp1[2],1),'0'):'';
$Dec2=isset($Tmp2[2])?rtrim(substr($Tmp2[2],1),'0'):'';
$DLen=max(strlen($Dec1),strlen($Dec2));
if($Scale==null) $Scale=$DLen;
$Num1=strrev(ltrim($Tmp1[1],'0').str_pad($Dec1,$DLen,'0'));
$Num2=strrev(ltrim($Tmp2[1],'0').str_pad($Dec2,$DLen,'0'));
$MLen=max(strlen($Num1),strlen($Num2));
$Num1=str_pad($Num1,$MLen,'0');
$Num2=str_pad($Num2,$MLen,'0');
for($i=0;$i<$MLen;$i++) {
$Sum=((int)$Num1{$i}+(int)$Num2{$i});
if(isset($Output[$i])) $Sum+=$Output[$i];
$Output[$i]=$Sum%10;
if($Sum>9) $Output[$i+1]=1;
}
$Output=strrev(implode($Output));
$Decimal=str_pad(substr($Output,-$DLen,$Scale),$Scale,'0');
$Output=(($MLen-$DLen<1)?'0':substr($Output,0,-$DLen));
$Output.=(($Scale>0)?".{$Decimal}":'');
return($Output);
}
$A="5650175242.508133742";
$B="308437806.831153821478770";
printf(" Add(%s,%s);\r\n// %s\r\n\r\n",$A,$B, Add($A,$B));
printf("BCAdd(%s,%s);\r\n// %s\r\n\r\n",$A,$B,BCAdd($A,$B));
?>
It was a fun experience making, and thought I'd share it.
Enjoy,
Nitrogen.