PDA

Click to See Complete Forum and Search --> : Formating Strings


titan7262
Jan 3rd, 2006, 06:50 PM
How can I format a string from an input value '1' to '01' then typecasting it to string?

Thanks!

visualAd
Jan 4th, 2006, 06:24 AM
I am confused. It would always be a string. :confused:

$input = 1;

$input = '0' . $input; // it is a string

CornedBee
Jan 4th, 2006, 07:00 AM
If you want the result to have two digits, even if the input has two digits, you can use sprintf:
$string = sprintf("%02d", $input);

Note that types aren't very important in PHP.

PlaGuE
Jan 4th, 2006, 07:40 PM
but what if the input has 3 or more?...

wouldnt it be better to always add a 0 to the input. or if 2 dont add zero. else add a zero

CornedBee
Jan 5th, 2006, 05:07 AM
but what if the input has 3 or more?...
Then the result would still have 3 digits. Field width specifiers never truncate.

wouldnt it be better to always add a 0 to the input. or if 2 dont add zero. else add a zero
That would be far more complex, for no gain.