views:

125

answers:

3

I'm unsure how to prepend the number 0 to a number in javascript.

Example input would be 1234, and this would wind up as 01234. Everything I try keeps adding the number zero, as opposed to prepending (obviously). Is there some way to escape the character, or some specific syntax for this?

This is for chrome.

+2  A: 
String(0) + 123

or

"" + 0 +123
Adam
+1  A: 
alert('0' + String(1234));

Using String() is a nice way to cast from number to string in javascript. The quotes around the '0' make sure that it, too, is a string. Thus, the + is going to do string concatenation instead of addition.

Funka
+3  A: 
function prepend(num){
    return '0'+num;
}

var num = 123;

alert(prepend(num));

//output is an alert box with this text: 0123
Cam