Forum Moderators: coopster

Message Too Old, No Replies

PHP adding leading Zeros

         

AndyD

8:38 pm on Jun 29, 2004 (gmt 0)

10+ Year Member



Is there a quick way to format numbers with leading zero's?

So 1, 2, 3 become 001 002 003 in a database?

Cheers,

Andrew

JasonHamilton

8:38 pm on Jun 29, 2004 (gmt 0)

10+ Year Member



If you're using mysql, you could set that in the database instead of using php to do it.

AndyD

9:15 pm on Jun 29, 2004 (gmt 0)

10+ Year Member



I am using mysql. Where would I enter this in the database using PHPAdmin? The only fields are

Field, Type, Length/Values, Attributes, Null, Default, Extra?

I assume I need to put 000 into one of these?

Thanks,

Andrew

Romeo

9:22 pm on Jun 29, 2004 (gmt 0)

10+ Year Member



... or convert it on the fly with
$x = 1;
$y = sprintf("%03d",$x);
echo $y;

Regards,
R.

coopster

9:22 pm on Jun 29, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



With MySQL? Have a look at the LPAD [dev.mysql.com] function when you INSERT or UPDATE the data.

With PHP or Perl have a look at the printf and sprintf functions.

denny

8:32 am on Jul 2, 2004 (gmt 0)

10+ Year Member



TYPE: tinyint
LENGTH: 3
ATTRIBUTES: UNSIGNED ZEROFILL

coopster

1:03 pm on Jul 2, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Welcome to WebmasterWorld, denny, and good call!

You could define the column with the optional extension attribute

ZEROFILL
and then the default padding of spaces is replaced with zeros. For example, for a column declared as TINYINT ZEROFILL, a value of 7 is retrieved as 007.

Note however that it is unnecessary to define the

UNSIGNED
attribute if you specify
ZEROFILL
for a numeric column as MySQL automatically adds the
UNSIGNED
attribute for you.

AndyD

5:17 pm on Jul 2, 2004 (gmt 0)

10+ Year Member



That worked a treat. I thought I was doing something silly, but couldn't see it.

Easy when you know how ;)

Andrew