Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: Convert number to 2 digits

1. ## Convert number to 2 digits

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:
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++;```

• 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

• I'm only a bit of a newbie editing someone elses code so how would i go about doing that in this example?

• At least give it a go and post what you come up with. If you dont try, you'll never learn.

• It's not that hard. You know the variable that needs changing, so look at the examples given on the page shown.

PHP Code:
``` str_pad (\$input, \$pad_length, \$pad_string, \$pad_type)  ```
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.
PHP Code:
``` str_pad (\$day_num, 2, "0", STR_PAD_LEFT)  ```
So put that where \$day_num is in your code

• I wrote a function for exactly the same thing, hope it helps:

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

•

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•