Zero fill a number
By: Daniel
Have you ever needed to make sure your number is a certain length for output? Say you have the number 5 but need to make sure it is 3 digits and out put like: 005. How would you go about this? One way to do this is the following:
function zerofill ($num,$zerofill) { // Get the current string length of the original number // Loop through that number until it has reached the count in $zerofill while (strlen($num)<$zerofill) { $num = "0".$num; } return $num; }
The usage of this code would be:
// Output will be 005 echo zerofill(5, 3);
Enjoy!






















March 25th, 2009 at 4:55 am
Nice! I’m looking for something like that..
April 8th, 2009 at 3:27 am
it’s like echo sprintf(“s”, 5);
April 8th, 2009 at 4:12 am
Did You know that there is a php function str_pad
It does the same, and even more
check it
May 25th, 2009 at 9:38 am
[...] Learn how to make a number a certain amount of characters. Such as 5 you could make to 005. http://www.wlscripting.com/tutorial/55 [...]
May 25th, 2009 at 4:34 pm
As sLn said, there is a built-in function, named str_pad.
Btw, I advice you to upgrade your Wordpress to the latest stable version to prevent hacks and attacks.
August 17th, 2009 at 8:41 am
[...] 15. Zero fill a number [...]
August 28th, 2009 at 6:48 am
Now show us how to do a php zero fill bitwise operation (ie. like the >>> operator in JavaScript).
Points to sLn
December 11th, 2009 at 2:52 pm
http://php.net/manual/de/function.sprintf.php
string sprintf ( string $format [, mixed $args [, mixed $... ]] )
wold be better than a loop
December 14th, 2009 at 9:16 am
[...] 15. Zero fill a number [...]