PDA

View Full Version : Convert number to 2 digits

denhamd2
04-04-2007, 03:40 PM
hi guys,

I have a variable \$day_num which contains the day of the month, but if its 1-9 it only displays as "1" or "9", I'm looking to convert the variable to display as 2 digits, ie. "01", or "09", etc. any ideas?

Here's my code:

//sets the first day of the month to 1
\$day_num = 1;

//count up the days, untill we've done all of them in the month

while
( \$day_num <= \$days_in_month )
{

echo "<td>\$day_num<br><input name=\"\$day_num\$month\$year\" type=\"checkbox\" value=\"yes\"></td>\n";
\$day_num++;
\$day_count++;

NancyJ
04-04-2007, 03:50 PM

04-04-2007, 03:54 PM
Edit: Too late, basically says the same as above ^^

Of the dozen ways you could do this, the str_pad(...) function is one way - http://php.net/str_pad

denhamd2
04-04-2007, 04:08 PM
I'm only a bit of a newbie editing someone elses code so how would i go about doing that in this example?

NancyJ
04-04-2007, 04:16 PM
At least give it a go and post what you come up with. If you dont try, you'll never learn.

Nightfire
04-04-2007, 04:17 PM
It's not that hard. You know the variable that needs changing, so look at the examples given on the page shown.

You know what \$input is as you mentioned what the variable name is in your original post.
You know the length, as you want 2 numbers showing.
You know what you want to pad the variable with, as you mentioned you wanted 0's
And the direction of the pad is from the left.

So put that where \$day_num is in your code

guvenck
04-04-2007, 04:22 PM
I wrote a function for exactly the same thing, hope it helps:

function dotwodigits(\$val) {
if (intval(\$val) < 10) {
\$twodigits = "0\$val";
}
elseif (intval(\$val) >= 10) {
\$twodigits = \$val;
}
return \$twodigits;
}