Show a leading zero if a number is less than 10

JavascriptMathNumbersDigits

Javascript Problem Overview


> Possible Duplicate:
> JavaScript equivalent to printf/string.format
> How can I create a Zerofilled value using JavaScript?

I have a number in a variable:

var number = 5;

I need that number to be 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 a 0 to it as a string, but I was hoping there's a JS function that would do it?

Javascript Solutions


Solution 1 - Javascript

There's no built-in JavaScript function to do this, but you can write your own fairly easily:

function pad(n) {
	return (n < 10) ? ("0" + n) : n;
}

EDIT:

Meanwhile there is a native JS function that does that. See String#padStart

console.log(String(5).padStart(2, '0'));

Solution 2 - Javascript

Try this

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/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNicekiwiView Question on Stackoverflow
Solution 1 - JavascriptChris FulstowView Answer on Stackoverflow
Solution 2 - JavascriptWazyView Answer on Stackoverflow