Prepend 0 to a number in Javascript
I'm unsure how to prepend the number 0 to a number in javascript.
Example input wo开发者_StackOverflow中文版uld 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.
function prepend(num){
return '0'+num;
}
var num = 123;
alert(prepend(num));
//output is an alert box with this text: 0123
String(0) + 123
or
"" + 0 +123
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.
精彩评论