80

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?

Community
  • 1
  • 1
Nicekiwi
  • 4,567
  • 11
  • 49
  • 88

2 Answers2

186

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'));
Vishnudev Krishnadas
  • 10,679
  • 2
  • 23
  • 55
Chris Fulstow
  • 41,170
  • 10
  • 86
  • 110
  • 12
    Or `...n < 10 && n >=0...`, so you don't end up with "0-5". – nnnnnn Nov 11 '11 at 06:21
  • 2
    Taking care of negavite upto 10 as well: function pad(n) { if (n < 10 & n >=0) return ("0" + n); if(n < 0 & n > -11) return ("-0" + Math.abs(n)); return n; } – Abs Apr 01 '14 at 09:48
  • 1
    Nice one about the `padStart()` function. – Kurt Van den Branden Jan 24 '19 at 08:05
  • 1
    FYI, according to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart Internet Explorer does not support `padStart`. – Gavin Jun 05 '19 at 08:54
12

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/

Wazy
  • 8,822
  • 10
  • 53
  • 98
  • 4
    read his last sentence...he knows how to do that already, he was looking for a format function i believe. – mpen Nov 11 '11 at 05:07