Show a leading zero if the number is less than 10

Possible duplicate:
JavaScript equivalent to printf / string.format
How to create a Zerofilled value using JavaScript?

I have a number in a variable:

var number = 5; 

I need this number to output as 05:

 alert(number); // I want the alert to display 05, rather than 5. 

How can i do this?

I could manually check the number and add 0 to it as a string, but I was hoping there would be a JS function?

+49
javascript math numbers digits
Nov 11 2018-11-11T00:
source share
2 answers

There is no built-in JavaScript function for this, but you can easily write your own:

 function pad(n) { return (n < 10) ? ("0" + n) : n; } 
+103
Nov 11 2018-11-11T00:
source share

Try

 function pad (str, max) { return str.length < max ? pad("0" + str, max) : str; } alert(pad("5", 2)); 

Example

http://jsfiddle.net/

Or

 var number = 5; var i; if (number < 10) { alert("0"+number); } 

Example

http://jsfiddle.net/

+10
Nov 11 '11 at 5:05
source share



All Articles