Page 1 of 1

Leading Zeros

Posted: Wed Nov 25, 2009 2:21 pm
by spacebiscuit
Hi,

I am trying to find a way of adding leading zeros to a number.

sprintf does not work because it always adds x number of zeros. This is no good in the following example:

9 becomes 0009
10 becomes 00010

10 should become 0010.

I hope that makes sense?

Rob.

Re: Leading Zeros

Posted: Wed Nov 25, 2009 2:26 pm
by superdezign

Re: Leading Zeros

Posted: Wed Nov 25, 2009 2:43 pm
by spacebiscuit
Same problem..... it adds the same number of zeros to all cases.

Re: Leading Zeros

Posted: Wed Nov 25, 2009 2:48 pm
by superdezign
Then you are doing it wrong.

Code: Select all

echo str_pad($input, 4, '0', STR_PAD_LEFT);
Also, it shouldn't make a difference, but make sure that $input is a string.

Re: Leading Zeros

Posted: Wed Nov 25, 2009 3:25 pm
by spacebiscuit
Maybe that is the problem - the input is not a string it is an int. The above example does not work.

Rob.

Re: Leading Zeros

Posted: Wed Nov 25, 2009 7:44 pm
by spacebiscuit
My error - str_pad does the trick. I just forgot to remove the leading 0 i had hardcoded into my my testing environment - opps!

Code: Select all

str_pad((int) $x,4,"0",STR_PAD_LEFT))
Many thanks,

Rob.

Re: Leading Zeros

Posted: Wed Nov 25, 2009 10:40 pm
by requinix