1

I tried the accepted answer which i found here but the accepted answer does not add leading zero if number is like -9, -8, -7 etc.

I want to append a zero if a number is single digit in both cases if positive or negative like,

+9 => +09
-9 => -09

Any suggestions?

Community
  • 1
  • 1
Khawer Zeshan
  • 9,470
  • 6
  • 40
  • 63
  • 1
    you could check the length of the variable and the first character, if the length is 1 add a leading 0, if the length is 2 and the first character is -, add a 0 in the middle – zajd Mar 20 '13 at 15:29
  • assume this number 50, its length is also 2 so it will add the 0 before 50 and it will become 050 which i don't want. As i only want to append zero on a single digit number – Khawer Zeshan Mar 20 '13 at 15:31
  • if the length is 2 AND the first character is - – zajd Mar 20 '13 at 15:35

2 Answers2

4
echo sprintf('%+03d', $number);
deceze
  • 510,633
  • 85
  • 743
  • 889
1

You could do something like this

function addZero($number)

   switch(strLen($number)) {

      case 1:
          return "0" . $number;
          break;

      case 2:
          if (substr($number, 0) == "-") return "-0" . substr($number, 1);
          break;

   }

   return $number

}
zajd
  • 761
  • 1
  • 5
  • 18