format number with leading 0's ?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
gmrobert
Forum Newbie
Posts: 22
Joined: Wed Oct 04, 2006 9:07 am

format number with leading 0's ?

Post 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
User avatar
bokehman
Forum Regular
Posts: 509
Joined: Wed May 11, 2005 2:33 am
Location: Alicante (Spain)

Post by bokehman »

Integers don't have leading zeros. Convert the number to a string and then pad it based on string length.
Last edited by bokehman on Sat Nov 04, 2006 6:33 am, edited 1 time in total.
User avatar
Cameri
Forum Commoner
Posts: 87
Joined: Tue Apr 12, 2005 4:12 pm
Location: Santo Domingo, Dominican Republic

Post by Cameri »

Hope this helps:

Code: Select all

<?php
$number = 30;
$length = 10;
echo str_pad($number, $length, "0", STR_PAD_LEFT);
?>
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

Offcourse there is already such a function: http://www.php.net/sprintf

eg: printf("[%010s]\n", 3000);
User avatar
bokehman
Forum Regular
Posts: 509
Joined: Wed May 11, 2005 2:33 am
Location: Alicante (Spain)

Post 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.
User avatar
Cameri
Forum Commoner
Posts: 87
Joined: Tue Apr 12, 2005 4:12 pm
Location: Santo Domingo, Dominican Republic

Post 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.
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post 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...)
gmrobert
Forum Newbie
Posts: 22
Joined: Wed Oct 04, 2006 9:07 am

Post by gmrobert »

Cameri,

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

Thanks

Greg
Post Reply