Page 1 of 1

format number with leading 0's ?

Posted: Sat Nov 04, 2006 6:23 am
by gmrobert
Is there a function that allows me to format a number with leading zeros?

ie. ensure a number is 8 digits:

3 == 00000003

300 == 00000300

300000 == 00300000


I can build my own function but I was wondering if there is a built in one.


Thanks

Greg

Posted: Sat Nov 04, 2006 6:29 am
by bokehman
Integers don't have leading zeros. Convert the number to a string and then pad it based on string length.

Posted: Sat Nov 04, 2006 6:32 am
by Cameri
Hope this helps:

Code: Select all

<?php
$number = 30;
$length = 10;
echo str_pad($number, $length, "0", STR_PAD_LEFT);
?>

Posted: Sat Nov 04, 2006 6:34 am
by timvw
Offcourse there is already such a function: http://www.php.net/sprintf

eg: printf("[%010s]\n", 3000);

Posted: Sat Nov 04, 2006 6:42 am
by bokehman
timvw wrote:Offcourse there is already such a function
There is no function that can make php pad an integer with leading zeros, only strings... The original post said a number. Strings may contain digits but they are not numbers.

Posted: Sat Nov 04, 2006 6:48 am
by Cameri
Well since he said formatting a number with leading zeros I automatically understood he meant a string, not a number.
There's no way you can add formating to any type without converting it to a string first, unless, of course, you are God.

Posted: Sat Nov 04, 2006 7:00 am
by timvw
bokehman wrote:
timvw wrote:Offcourse there is already such a function
There is no function that can make php pad an integer with leading zeros, only strings... The original post said a number. Strings may contain digits but they are not numbers.
The result of 'formatting' a number leads to a string..

But as the printf examples shows there is no need to convert the number to a string first (even there was such a need, php would probably take care of it...)

Posted: Sat Nov 04, 2006 8:06 am
by gmrobert
Cameri,

Thank you ... for understanding my obviously poorly worded request.

Thanks

Greg