1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Number Formatting

Discussion in 'PHP' started by pradeep, Aug 5, 2006.

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,646
    Likes Received:
    86
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    Many times we require to format a number to output with thousand place comma separator, here is a function will help you do so.

    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;
     }
     

Share This Page