_
_ Handy PHP
_
_
Tutorials, Scripts, Information And Other Resources arrow Forum
Saturday, 06 September 2008
_

Refer A Friend using Revolution Money Exchange
Resource Menu
Handy PHP Store
Free Domain Name
PHP Functions
PHP Downloads
PHP Newsfeeds
PHP Tutorials
Webmaster Tools
User Login
TalkPHP
Get friendly help with your PHP problems for free.
www.talkphp.com
The PHP Resource Index
Handy PHP
Free PHP Help!

FireBoard
Welcome, Guest
Please Login or Register.    Lost Password?
Rules
Description:
  stringleading_zeros(string number, int places)
     
  This function is handy if you need to add leading zeros to a number for various reason.  The most obvious reason to add leading zeros would be to create numberic or alph-numeric file names that you want to ensure are sorted correctly.
   
 
Function:
  function leading_zeros($value, $places){
// Function written by Marcus L. Griswold (vujsa)
// Can be found at http://www.handyphp.com
// Do not remove this header!

    if(is_numeric($value)){
        for($x = 1; $x <= $places; $x++){
            $ceiling = pow(10, $x);
            if($value < $ceiling){
                $zeros = $places - $x;
                for($y = 1; $y <= $zeros; $y++){
                    $leading .= "0";
                }
            $x = $places + 1;
            }
        }
        $output = $leading . $value;
    }
    else{
        $output = $value;
    }
    return $output;
}
   
 
Usage:
  echo leading_zeros('654321', 10);
     
Result:
  0000654321
     
Notes:
  You must use either single or double quotes in the first argument of the function call.  Failure to do so will result in an undesirable number format.  If your output is displayed in an exponential format, you probably left out your quotes.  Additionally, any variable used in the first argument must contain a string and not a number.

For example,

$value = 1234567890987654321;

Doesn't work but,

$value = '1234567890987654321';

Does work! 


In the example above,'654321' is the number which you want to format and10 is the total number of digits including all of the zeros and numbers in the value.


I most cases the PHP function str_pad will work as well or better and is more efficient.  Additionally, str_pad doesn't care if the value is numeric or not.



{mos_fb_discuss:3}
Powered by FireBoardget the latest posts directly to your desktop

_
 
_
_
© 2008 Handy PHP