gerkintrigg Posted August 2, 2007 Share Posted August 2, 2007 I'm trying to work out how to format a variable as two digits even if it's one... so: 1 becomes 01, 2 becomes 02, but 10 stays as 10... is there an easy way? i tried number_format but that seems to only be for float vars. thanks. Link to comment https://forums.phpfreaks.com/topic/63023-adding-a-zero-to-an-integer/ Share on other sites More sharing options...
Gamic Posted August 2, 2007 Share Posted August 2, 2007 Try something like this: function 1_to_2($number){ $str="".$number;//convert the number to a string if(strlen($str)==1){//if the number has only 1 digit $str="0".$str;//add another } return $str;//return the number } Link to comment https://forums.phpfreaks.com/topic/63023-adding-a-zero-to-an-integer/#findComment-313862 Share on other sites More sharing options...
Vizor Posted August 2, 2007 Share Posted August 2, 2007 Will sprintf() not do it? Link to comment https://forums.phpfreaks.com/topic/63023-adding-a-zero-to-an-integer/#findComment-313863 Share on other sites More sharing options...
Gamic Posted August 2, 2007 Share Posted August 2, 2007 Probably. Have a look at the manual entry for it. http://uk.php.net/sprintf Link to comment https://forums.phpfreaks.com/topic/63023-adding-a-zero-to-an-integer/#findComment-313865 Share on other sites More sharing options...
Vizor Posted August 2, 2007 Share Posted August 2, 2007 <?php $var = 1; printf('Value is %02d', $var); // returns Value is 01 ?> Link to comment https://forums.phpfreaks.com/topic/63023-adding-a-zero-to-an-integer/#findComment-313869 Share on other sites More sharing options...
gerkintrigg Posted August 2, 2007 Author Share Posted August 2, 2007 hmm thanks. Link to comment https://forums.phpfreaks.com/topic/63023-adding-a-zero-to-an-integer/#findComment-313911 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.