0

Don't feel foolishness in my question. Below is my scenario. Please advice

var num = 02; var add = num + 1 ;

Getting result is 3, but I need it as 03. Is it possible.

user1817630
  • 135
  • 4
  • Do you mean you need a _string_ with the characters "01" in it? Or the "octal representation"? How do you intend to use this value of `03`? – Floris Feb 21 '13 at 11:45
  • Possible duplicate of http://stackoverflow.com/q/1267283/2034234 – Ruben Infante Feb 21 '13 at 11:45
  • I don't need it as a string. I need to increment and decrement the value according to my purpose. – user1817630 Feb 21 '13 at 11:47
  • you need add as 03 in where? – 999k Feb 21 '13 at 11:47
  • possible duplicate of [How do I format 7 as '07' in string in JavaScript?](http://stackoverflow.com/questions/10864288/how-do-i-format-7-as-07-in-string-in-javascript) – JJJ Feb 21 '13 at 11:47
  • 1
    If you don't need it as a string, what do you need it as? If you're doing addition, the trailing 0 is superfluous... – BenM Feb 21 '13 at 11:48
  • guys my scenario is totally different. I need an output like my query. For you better understanding I have given simple example. – user1817630 Feb 21 '13 at 11:53
  • "For your better understanding".... Clearly as given nobody understands what you are asking, how is `03` different from `3` _except_ when represented as a string?.... Are you outputting this result? Printing it? – Floris Feb 21 '13 at 11:58

2 Answers2

0

You'll need to write a padding function:

function strpad(string, length, padChar) 
{
    var o = string.toString();
    if(!padChar) 
    { 
       padChar = '0'; 
    }

    while (o.length < length) 
    {
        o = padChar + o;
    }
    return o;
};

And then call it using:

var num = 3;
var add = strpad((3 + 1), 2); // will return '04' as a string.
Floris
  • 45,857
  • 6
  • 70
  • 122
BenM
  • 52,573
  • 26
  • 113
  • 168
0

you can do it like this

<script>
var num=2;
var add= parseInt(num + 2);

if(parseInt(add) <10)
   {
      add= '0'+add; // if single digit no. then concat 0 before the no.
   }

</script>
Saswat
  • 12,320
  • 16
  • 77
  • 156