[javascript] How to format numbers by prepending 0 to single-digit numbers?

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?

This question is related to javascript number-formatting

The answer is


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"

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)

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

@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');

This is a very nice and short solution:

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

My Example like this

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

and the output is 09


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.

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);
}

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

Regex is the best.


Improved version of previous answer

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


("0" + (date.getMonth() + 1)).slice(-2);
("0" + (date.getDay())).slice(-2);

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'.


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

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.


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')

    function colorOf(r,g,b){
  var f = function (x) {
    return (x<16 ? '0' : '') + x.toString(16) 
  };

  return "#" +  f(r) + f(g) + f(b);
}

My version:

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

_x000D_
_x000D_
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)));
_x000D_
_x000D_
_x000D_


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/


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;
  }
}

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;
};

<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>

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);
  }
}

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();
}

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);

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:

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

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

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


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

You can use the padStart method:

more info: https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/String/

check this example:

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

console.log(n( 9));  //print "09"
console.log(n(10));  //print "10"
console.log(n(999)); //print "999"
_x000D_
_x000D_
_x000D_


Here's the easiest solution I found:-

let num = 9; // any number between 0 & 99
let result = ( '0' + num ).substr( -2 );

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

_x000D_
_x000D_
function zeroPad(numberStr) {_x000D_
  return numberStr.padStart(2, "0");_x000D_
}_x000D_
_x000D_
var numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];_x000D_
_x000D_
numbers.forEach(_x000D_
  function(num) {_x000D_
    var numString = num.toString();_x000D_
    _x000D_
    var paddedNum = zeroPad(numString);_x000D_
_x000D_
    console.log(paddedNum);_x000D_
  }_x000D_
);
_x000D_
_x000D_
_x000D_


Quick and dirty one liner....

function zpad(n, len) {
  return 0..toFixed(len).slice(2,-n.toString().length)+n.toString();
}

This is simple and works pretty well:

function twoDigit(number) {
  var twodigit = number >= 10 ? number : "0"+number.toString();
  return twodigit;
}

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)

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

const formatNumber = n => ("0" + n).slice(-2);

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);
}