Go4Expert

Go4Expert (http://www.go4expert.com/)
-   PHP (http://www.go4expert.com/articles/php-tutorials/)
-   -   Number Formatting (http://www.go4expert.com/articles/number-formatting-t1129/)

pradeep 5Aug2006 15:05

Number Formatting
 
Many times we require to format a number to output with thousand place comma separator, here is a function will help you do so.

Code: PHP

function numcomma ($value)
 {
     if(strpos($value,"."))
     {
         $decimalval = substr($value,strpos($value,".")+1);
         $value = substr($value,0,strpos($value,"."));
     }
 
     $length = strlen($value);
 
     for($i=3;$i<($length);$i=$i+3)
     {
         $k = $i*(-1);
         $chunks[count($chunks)] = substr($value,$k,3);
     }
 
     $inarray = count($chunks)*3;
     $leftout = $length-$inarray;
     $leftout = substr($value,0,$leftout);
 
     $finaltext = $leftout;
 
     rsort($chunks);
 
     for($i=0;$i<count($chunks);$i++)
     {
         $finaltext .= "," .$chunks[$i];
     }
 
     if(strlen($decimalval)>0) $finaltext .= "." .$decimalval;
 
     return $finaltext;
 }



All times are GMT +5.5. The time now is 23:34.