449

I want to format a number to have two digits. The problem is caused when 09 is passed, so I need it to be formatted to 0009.

Is there a number formatter in JavaScript?

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Keith Power
  • 13,891
  • 22
  • 66
  • 135
  • 2
    possible duplicate of [JavaScript: formatting number with exactly two decimals](http://stackoverflow.com/questions/1726630/javascript-formatting-number-with-exactly-two-decimals) – Oleg Mar 19 '15 at 10:07
  • not duplicate. here asks for prepending (0001, 0002) not after decimal point 0.001 0.002 – Eran W Mar 23 '21 at 11:37
  • Possible using `str.padStart(2, '0'));` See this answer: https://stackoverflow.com/a/66344598/648298 – Eran W Mar 23 '21 at 11:38

36 Answers36

802

Edit (2021):

It's no longer necessary to format numbers by hand like this anymore. This answer was written way-back-when in the distant year of 2011 when IE was important and babel and bundlers were just a wonderful, hopeful dream.

I think it would be a mistake to delete this answer; however in case you find yourself here, I would like to kindly direct your attention to the second highest voted answer to this question as of this edit.

It will introduce you to the use of .toLocaleString() with the options parameter of {minimumIntegerDigits: 2}. Exciting stuff. Below I've recreated all three examples from my original answer using this method for your convenience.

[7, 7.5, -7.2345].forEach(myNumber => {
  let formattedNumber = myNumber.toLocaleString('en-US', {
    minimumIntegerDigits: 2,
    useGrouping: false
  })
  console.log(
    'Input:    ' + myNumber + '\n' +
    'Output:   ' + formattedNumber
  )
})

Original Answer:

The best method I've found is something like the following:

(Note that this simple version only works for positive integers)

var myNumber = 7;
var formattedNumber = ("0" + myNumber).slice(-2);
console.log(formattedNumber);

For decimals, you could use this code (it's a bit sloppy though).

var myNumber = 7.5;
var dec = myNumber - Math.floor(myNumber);
myNumber = myNumber - dec;
var formattedNumber = ("0" + myNumber).slice(-2) + dec.toString().substr(1);
console.log(formattedNumber);

Lastly, if you're having to deal with the possibility of negative numbers, it's best to store the sign, apply the formatting to the absolute value of the number, and reapply the sign after the fact. Note that this method doesn't restrict the number to 2 total digits. Instead it only restricts the number to the left of the decimal (the integer part). (The line that determines the sign was found here).

var myNumber = -7.2345;
var sign = myNumber?myNumber<0?-1:1:0;
myNumber = myNumber * sign + ''; // poor man's absolute value
var dec = myNumber.match(/\.\d+$/);
var int = myNumber.match(/^[^\.]+/);

var formattedNumber = (sign < 0 ? '-' : '') + ("0" + int).slice(-2) + (dec !== null ? dec : '');
console.log(formattedNumber);
Joseph Marikle
  • 76,418
  • 17
  • 112
  • 129
  • 4
    @KeithPower that demo doesn't illustrate this – Joseph Marikle Nov 07 '11 at 21:49
  • 1
    @KeithPower Here's a demo that illustrates the above method: http://jsfiddle.net/bkTX3/. Click on the box, change the value, and click off the box to see it in action. – Joseph Marikle Nov 07 '11 at 21:53
  • 1
    @Joseph .75 is transformed in 75. – Galled Nov 25 '11 at 22:06
  • @Galled normally that kind of thing is not needed with this form of formatting in my experience, but I've thrown together an edit that would cover that scenario. – Joseph Marikle Nov 26 '11 at 02:09
  • Also have a look at `.toPrecision()` method http://www.w3schools.com/jsref/jsref_toprecision.asp – Oleg Mar 19 '15 at 10:10
  • what about negative input values? -75 will become 75. – Alex Apr 27 '17 at 12:42
  • @Alex Yeah, that is the case. However, I'm not familiar with any cases where negative numbers are formatted as `-00` or `-08`. Not saying it's impossible for that to be needed, but I find it at the least unlikely to come up. I would suggest for that case to first determine the sign of the value, store it for later, and use the above code on the absolute value of the number. Then once you have that formatted string representing the number, prepend a `-` accordingly. – Joseph Marikle Apr 27 '17 at 13:07
  • @JosephMarikle:just pointing out that a formating function should not change the semantings of the value, but only the appearance. The code above is dangerous, because it might hide other bugs even in situations where no negative values are expected. I used the code and it worked well until a negative value should be displayed. The good thing is that I caught this bug early. – Alex Apr 28 '17 at 14:48
  • @Alex Interesting. I'll work on improving it. Do you have any suggestions on the issue? My first thought is to, as I said, run the code against the absolute value and reapply the sign after the fact. – Joseph Marikle Apr 28 '17 at 14:50
  • Maybe just add following, since it's not clear how negative values should be formatted? `if( value < 0 || value > 99 ){ return '' + value; }` The same problem arises for inputs > 99 and floats btw. So maybe add code for testing for that as well :-P – Alex Apr 28 '17 at 15:08
  • @Alex I've put together a third case. Hopefully that covers it. We'll see I suppose. :P – Joseph Marikle Apr 28 '17 at 15:13
  • I also added if (myNumber=== "0") myNumber.value = "00"; to make sure that if 0 is entered it will appear as 00 – Ciaran Gallagher Jan 23 '20 at 09:20
  • Brilliant! This was EXACTLY what I needed. Thank you! – kevin walker Feb 20 '21 at 19:26
  • I still appreciate the original answer over the localeString call since it allows one to use a different radix – Krzysztof Krzeszewski Oct 04 '22 at 07:51
253

Use the toLocaleString() method in any number. So for the number 6, as seen below, you can get the desired results.

(6).toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false})

Will generate the string '06'.

nyteshade
  • 2,712
  • 1
  • 14
  • 9
156

If the number is higher than 9, convert the number to a string (consistency). Otherwise, add a zero.

function n(n){
    return n > 9 ? "" + n: "0" + n;
}

n( 9); //Returns "09"
n(10); //Returns "10"
n(999);//Returns "999"
Rob W
  • 341,306
  • 83
  • 791
  • 678
65

In all modern browsers you can use

numberStr.padStart(2, "0");

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart

function zeroPad(numberStr) {
  return numberStr.padStart(2, "0");
}

var numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

numbers.forEach(
  function(num) {
    var numString = num.toString();
    
    var paddedNum = zeroPad(numString);

    console.log(paddedNum);
  }
);
Lifehack
  • 1,981
  • 15
  • 12
  • 3
    Be aware this isn't supported in IE at all https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart#Browser_compatibility – Tim Feb 16 '18 at 11:48
  • Also it doesn't work in some older versions of node (possibly anything older than node 8) – JSilv Sep 11 '18 at 20:39
  • As of now (2022) this is supported in all browsers. This is definitely the simplest answer in this thread. – BlueLite Nov 13 '22 at 07:04
57

Here's a simple number padding function that I use usually. It allows for any amount of padding.

function leftPad(number, targetLength) {
    var output = number + '';
    while (output.length < targetLength) {
        output = '0' + output;
    }
    return output;
}

Examples:

leftPad(1, 2) // 01
leftPad(10, 2) // 10
leftPad(100, 2) // 100
leftPad(1, 3) // 001
leftPad(1, 8) // 00000001
timrwood
  • 10,611
  • 5
  • 35
  • 42
36

@Lifehack's answer was very useful to me; where I think we can do it in one line for positive numbers

 String(input).padStart(2, '0');
Jee Mok
  • 6,157
  • 8
  • 47
  • 80
24

You can use the padStart method:

more info: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart

check this example:

function n(num, len = 2) {
  return `${num}`.padStart(len, '0');
}

console.log(n( 9));   //print "09"
console.log(n(10));   //print "10"
console.log(n(999));  //print "999"
console.log(n(999,6));//print "000999"
fitorec
  • 4,257
  • 2
  • 24
  • 18
13
("0" + (date.getMonth() + 1)).slice(-2);
("0" + (date.getDay())).slice(-2);
Stark
  • 131
  • 1
  • 3
10

You can do:

function pad2(number) {
   return (number < 10 ? '0' : '') + number
}

Example:

document.write(pad2(0) + '<br />');
document.write(pad2(1) + '<br />');
document.write(pad2(2) + '<br />');
document.write(pad2(10) + '<br />');
document.write(pad2(15) + '<br />');

Result:

00
01
02
10
15
fanaur
  • 117
  • 1
  • 3
9

It seems you might have a string, instead of a number. use this:

var num = document.getElementById('input').value,
    replacement = num.replace(/^(\d)$/, '0$1');
document.getElementById('input').value = replacement;

Here's an example: http://jsfiddle.net/xtgFp/

Joe
  • 80,724
  • 18
  • 127
  • 145
8

Here is a very simple solution that worked well for me.

First declare a variable to hold your number.

var number;

Now convert the number to a string and hold it in another variable;

var numberStr = number.toString();

Now you can test the length of this string , if it is less than desired you can append a 'zero' at the beginning.

if(numberStr.length < 2){
      number = '0' + number;
}

Now use the number as desired

console.log(number);
Edgar256
  • 702
  • 9
  • 13
7

Quick and dirty one liner....

function zpad(n, len) {
  return 0..toFixed(len).slice(2,-n.toString().length)+n.toString();
}
pwuk
  • 101
  • 1
  • 2
  • 1
    Excellent job. It's better to use this as extension method like this: `Number.prototype.leftPad = String.prototype.leftPad = function (pad) { return 0..toFixed(pad).slice(2, -this.toString().length) + this.toString(); };` – ConductedClever Jan 05 '19 at 06:24
7

Here's the easiest solution I found:-

let num = 9; // any number between 0 & 99
let result = ( '0' + num ).substr( -2 );
Bassam
  • 87
  • 1
  • 10
6

This is simple and works pretty well:

function twoDigit(number) {
  var twodigit = number >= 10 ? number : "0"+number.toString();
  return twodigit;
}
nickolusroy
  • 94
  • 1
  • 2
6

My version:

`${Math.trunc(num / 10)}${Math.trunc(num % 10)}`;

const func = (num) => `${Math.trunc(num / 10)}${Math.trunc(num % 10)}`;

const nums = [1, 3, 5, 6, 8, 9, 10, 20, 56, 80];
nums.forEach(num => console.log(func(num)));
user9949678
  • 61
  • 1
  • 3
5

I know this is an ancient post, but I wanted to provide a more flexible and OO solution option.

I've extrapolated the accepted answer a bit and extended javascript's Number object to allow for adjustable zero padding:

Number.prototype.zeroPad = function(digits) {
  var loop = digits;
  var zeros = "";
  while (loop) {
    zeros += "0";
    loop--;
  }
  return (this.toString().length > digits) ?
    this.toString() : (zeros + this).slice(-digits);
}
var v = 5;
console.log(v.zeroPad(2)); // returns "05"
console.log(v.zeroPad(4)); // returns "0005"

Edit: Add code to prevent cutting off numbers longer than your requested digits.

NOTE: This is obsolete in all but IE. Use padStart() instead.

Noah Duncan
  • 500
  • 1
  • 5
  • 18
5

Improved version of previous answer

function atLeast2Digit(n){
    n = parseInt(n); //ex. if already passed '05' it will be converted to number 5
    var ret = n > 9 ? "" + n: "0" + n;
    return ret;
}

alert(atLeast2Digit(5));
maszynka
  • 196
  • 4
  • 11
Anand Singh
  • 1,091
  • 13
  • 21
4

Updated for ES6 Arrow Functions (Supported in almost all modern browsers, see CanIUse)

const formatNumber = n => ("0" + n).slice(-2);
alistair
  • 565
  • 5
  • 15
4

There is not a built-in number formatter for JavaScript, but there are some libraries that accomplish this:

  1. underscore.string provides an sprintf function (along with many other useful formatters)
  2. javascript-sprintf, which underscore.string borrows from.
coltraneofmars
  • 221
  • 1
  • 2
3

or

function zpad(n,l){
   return rep(l-n.toString().length, '0') + n.toString();
}

with

function rep(len, chr) { 
   return new Array(len+1).join(chr);
}
pwuk
  • 101
  • 1
  • 2
3

If you want to limit your digits at the same time:

function pad2(number) {
  number = (number < 10 ? '0' : '') + number;
  number = number.substring(0,2);
  return number;
}

This would also chop of any value that exceeds two digits. I have been extending this upon fanaur's solution.

leopold
  • 1,971
  • 1
  • 19
  • 22
3

`${number}`.replace(/^(\d)$/, '0$1');

Regex is the best.

Son Tr.
  • 776
  • 6
  • 18
  • This appears to be almost exactly the same as [Joe's answer](https://stackoverflow.com/a/8043134/3088508) above. Please consider adding additional info to improve your answer, or delete it altogether. – Ethan Jun 08 '18 at 10:49
2
<html>
    <head>
        <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                $('#test').keypress(allowOnlyTwoPositiveDigts);
            });

            function allowOnlyTwoPositiveDigts(e){

                var test = /^[\-]?[0-9]{1,2}?$/
                return test.test(this.value+String.fromCharCode(e.which))
            }

        </script>
    </head>
    <body>
        <input id="test" type="text" />
    </body>
</html>
Victor Jatobá
  • 811
  • 7
  • 13
2

Here's a simple recursive solution that works for any number of digits.

function numToNDigitStr(num, n)
{
    if(num >=  Math.pow(10, n - 1)) { return num; }
    return "0" + numToNDigitStr(num, n-1);
}
2

If you don't have lodash in your project it will be an overkill to add the whole library just to use one function. This is the most sophisticated solution of your problem I've ever seen.

_.padStart(num, 2, '0')
kucherenkovova
  • 694
  • 9
  • 22
2

I built a pretty simple format function that I call whenever I need a simple date formatted. It deals with formatting single digits to double digits when they're less than 10. It kicks out a date formatted as Sat Sep 29 2018 - 00:05:44

This function is used as part of a utils variable so it's called as:

let timestamp = utils._dateFormatter('your date string');

var utils = {
  _dateFormatter: function(dateString) {
    let d = new Date(dateString);
    let hours = d.getHours();
    let minutes = d.getMinutes();
    let seconds = d.getSeconds();
    d = d.toDateString();
    if (hours < 10) {
      hours = '0' + hours;
    }
    if (minutes < 10) {
      minutes = '0' + minutes;
    }
    if (seconds < 10) {
      seconds = '0' + seconds;
    }
    let formattedDate = d + ' - ' + hours + ':' + minutes + ':' + seconds;
    return formattedDate;
  }
}
Roy Scheffers
  • 3,832
  • 11
  • 31
  • 36
Arq
  • 21
  • 1
2

My Example like this

         var n =9;
         var checkval=('00'+n).slice(-2);
         console.log(checkval)

and the output is 09

Aakash Sajjad
  • 97
  • 1
  • 5
2

You may also use Intl an ECMAScript International API that can customize your number as simple as this

let Number= Intl.NumberFormat('en-US', {
  minimumIntegerDigits: 2,
  minimumFractionDigits: 2
});

console.log(Number.format(2));
//02.00

and lots of embeded function that has Intl, you can put a prefix notation, signs and money format etc. for documentation just click here

Marvin
  • 647
  • 7
  • 15
1

Here's my version. Can easily be adapted to other scenarios.

function setNumericFormat(value) {
    var length = value.toString().length;
    if (length < 4) {
        var prefix = "";
        for (var i = 1; i <= 4 - length; i++) {
            prefix += "0";
        }
        return prefix + value.toString();
    }
    return  value.toString();
}
Veverke
  • 9,208
  • 4
  • 51
  • 95
1
    function colorOf(r,g,b){
  var f = function (x) {
    return (x<16 ? '0' : '') + x.toString(16) 
  };

  return "#" +  f(r) + f(g) + f(b);
}
Alexey Tseitlin
  • 1,031
  • 4
  • 14
  • 33
1

For anyone who wants to have time differences and have results that can take negative numbers here is a good one. pad(3) = "03", pad(-2) = "-02", pad(-234) = "-234"

pad = function(n){
  if(n >= 0){
    return n > 9 ? "" + n : "0" + n;
  }else{
    return n < -9 ? "" + n : "-0" + Math.abs(n);
  }
}
mjwrazor
  • 1,866
  • 2
  • 26
  • 42
1

my example would be:

<div id="showTime"></div>

    function x() {
    var showTime = document.getElementById("showTime");
    var myTime = new Date();
    var hour = myTime.getHours();
    var minu = myTime.getMinutes();
    var secs = myTime.getSeconds();
    if (hour < 10) {
        hour = "0" + hour
    };
    if (minu < 10) {
        minu = "0" + minu
    };
    if (secs < 10) {
        secs = "0" + secs
    };

    showTime.innerHTML = hour + ":" + minu + ":" + secs;
}

setInterval("x()", 1000)
DHJ
  • 31
  • 4
1

with this function you can print with any n digits you want

function frmtDigit(num, n) {
    isMinus = num < 0;
    if (isMinus)
        num *= -1;
    digit = '';
    if (typeof n == 'undefined')
        n = 2;//two digits
    for (i = 1; i < n; i++) {
        if (num < (1 + Array(i + 1).join("0")))
            digit += '0';
    }
    digit = (isMinus ? '-' : '') + digit + num;
    return digit;
};
jalmatari
  • 331
  • 5
  • 8
1

AS datatype in Javascript are determined dynamically it treats 04 as 4 Use conditional statement if value is lesser then 10 then add 0 before it by make it string E.g,

var x=4;
  x = x<10?"0"+x:x
 console.log(x); // 04
Siddhartha
  • 1,473
  • 14
  • 10
1

This is an old question, but wanted to add to it. In modern browsers you may use repeat which makes formatting simple for positive numbers:

('0'.repeat(digits - 1) + num).substr(-digits)

If you want support for IE and know the maximum number of digits (for instance, 10 digits):

('000000000' + num).substr(-digits)

For negative integers:

(num < 0 ? '-' : '') + ('000000000' + Math.abs(num)).substr(-digits)

With an explicit + for positive numbers:

['-', '', '+'][Math.sign(num) + 1] + ('000000000' + Math.abs(num)).substr(-digits)
Javier Elices
  • 2,066
  • 1
  • 16
  • 25
0

This is a very nice and short solution:

smartTime(time) {
  return time < 10 ? "0" + time.toString().trim() : time;
}
Porses
  • 11
  • 5