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.
Leading Zeros
Moderator: General Moderators
- superdezign
- DevNet Master
- Posts: 4135
- Joined: Sat Jan 20, 2007 11:06 pm
-
spacebiscuit
- Forum Contributor
- Posts: 390
- Joined: Mon Mar 07, 2005 3:20 pm
Re: Leading Zeros
Same problem..... it adds the same number of zeros to all cases.
- superdezign
- DevNet Master
- Posts: 4135
- Joined: Sat Jan 20, 2007 11:06 pm
Re: Leading Zeros
Then you are doing it wrong.
Also, it shouldn't make a difference, but make sure that $input is a string.
Code: Select all
echo str_pad($input, 4, '0', STR_PAD_LEFT);-
spacebiscuit
- Forum Contributor
- Posts: 390
- Joined: Mon Mar 07, 2005 3:20 pm
Re: Leading Zeros
Maybe that is the problem - the input is not a string it is an int. The above example does not work.
Rob.
Rob.
-
spacebiscuit
- Forum Contributor
- Posts: 390
- Joined: Mon Mar 07, 2005 3:20 pm
Re: Leading Zeros
My error - str_pad does the trick. I just forgot to remove the leading 0 i had hardcoded into my my testing environment - opps!
Many thanks,
Rob.
Code: Select all
str_pad((int) $x,4,"0",STR_PAD_LEFT))Rob.
Re: Leading Zeros
Or something that can treat numbers as numbers.
Code: Select all
sprintf("%04u", $x)