tags:

views:

1640

answers:

3

Hi

I need to cast single figures (1 to 9) to (01 to 09). I can think of a way but its big and ugly and cumbersome. I'm sure there must be some concise way. Any Suggestions

+17  A: 

First of all, your description is misleading. Double is a floating point data type. You presumably want to pad your digits with leading zeros in a string. The following code does that:

$s = sprintf("%02d", $digit);

For more information, refer to the documentation of sprintf.

Konrad Rudolph
A: 

You can use sprintf like Konrad wrote or simple if condition:

<?php
$digit = 9;
$s = strlen($digit)==1?('0'.$digit):$digit;
echo($s);
?>

This will echo 09.

Daok
You have a typo... springf
Jason Lepack
+6  A: 

There's also str_pad

<?php
$input = "Alien";
echo str_pad($input, 10);                      // produces "Alien     "
echo str_pad($input, 10, "-=", STR_PAD_LEFT);  // produces "-=-=-Alien"
echo str_pad($input, 10, "_", STR_PAD_BOTH);   // produces "__Alien___"
echo str_pad($input, 6 , "___");               // produces "Alien_"
?>
Jason Lepack