Number Formatting

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

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    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

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice