Wilco
Wilco

Reputation: 33364

How can I pad a value with leading zeros?

How can I pad a value with leading zeroes in JavaScript? I imagine I could build a custom function to pad zeros on to a typecasted value, but I'm wondering if there is a more direct way to do this?

Note: By padding the value I mean it in the database sense of the word (where a 6-digit padded representation of the number 5 would be "000005").

Upvotes: 605

Views: 354368

Answers (30)

TAHER El Mehdi
TAHER El Mehdi

Reputation: 9263

Here are five different ways to zero-fill a number in JavaScript:

  1. String.prototype.padStart():

    let n = 1;
    let zerofilled = n.toString().padStart(6, '0');
    console.log(zerofilled);
    
  2. String concatenation and slice:

    let n = 1;
    let zerofilled = ('000000' + n).slice(-6);
    console.log(zerofilled);
    
  3. String repeat:

    let n = 1;
    let zerofilled = '0'.repeat(6 - n.toString().length) + n;
    console.log(zerofilled);
    
  4. Convert to string and pad with Array join:

    let n = 1;
    let zerofilled = Array(7).join('0') + n;
    console.log(zerofilled.slice(-6));
    
  5. Convert to string and pad with Array fill:

    let n = 1;
    let zerofilled = (Array(6).fill('0').join('') + n).slice(-6);
    console.log(zerofilled);
    

Each of these solutions achieves zero-filling, and the best one depends on factors like readability, performance, and personal preference in the context of your specific use case.

Upvotes: 2

user4617883
user4617883

Reputation: 1498

This can be easily achieved with Intl.NumberFormat function:

const num = 5;
const formattedNum = new Intl.NumberFormat('en', { minimumIntegerDigits: 6, useGrouping: false }).format(num);
console.log(formattedNum);

Upvotes: 1

Benny Bottema
Benny Bottema

Reputation: 11513

Don't reinvent the wheel; use underscore string:

jsFiddle

var numToPad = '5';

alert(_.str.pad(numToPad, 6, '0')); // Yields: '000005'

Upvotes: 9

jasto salto
jasto salto

Reputation: 1

I use this snippet to get a five-digits representation:

(value+100000).toString().slice(-5) // "00123" with value=123

Upvotes: 12

Fabio Napodano
Fabio Napodano

Reputation: 1247

Variable-length padding function:

function addPaddingZeroes(value, nLength)
{
    var sValue = value + ''; // Converts to string

    if(sValue.length >= nLength)
        return sValue;
    else
    {
        for(var nZero = 0; nZero < nLength; nZero++)
            sValue = "0" + sValue;
        return (sValue).substring(nLength - sValue.length, nLength);
    }
}

Upvotes: 0

Dani bISHOP
Dani bISHOP

Reputation: 1289

Maybe I am to naive, but I think that this works in one simple and efficient line of code (for positive numbers):

padded = (value + Math.pow(10, total_length) + "").slice(1)

As long as you keep your length OK according to you set of values (as in any zero padding), this should work.

The steps are:

  1. Add the power of 10 with the correct number of 0's [69+1000 = 1069]
  2. Convert to string with +"" [1069 => "1069"]
  3. Slice the first 1, which resulted of first multiplication ["1069" => "069"]

For natural listings (files, dirs...) is quite useful.

Upvotes: 1

CuleroConnor
CuleroConnor

Reputation: 37

Mnah... I have not seen a "ultimate" answer to this issue and if you are facing the same challenge I must save you some time by saying that sadly there's not built-in function for that on JavaScript.

But there's this awesome function in PHP that does a great job on padding strings as well as numbers with single character or arbitrary strings. After some time of banging my head for not having the right tool on JavaScript (mostly for zerofillin' numbers and usually for trimming strings to fit a fixed length) and excessive coding work, I decided to write my own function.

It does the same ("almost the same"; read on for detail) that the dream PHP function does, but in comfortable client-side JavaScript:

function str_pad(input, pad_length, pad_string, pad_type) {
    var input = input.toString();
    var output = "";

    if((input.length > pad_length) &&
       (pad_type == 'STR_PAD_RIGHT')) {

        var output = input.slice(0, pad_length);
    }
    else
        if((input.length > pad_length) &&
           (pad_type == 'STR_PAD_LEFT')) {

            var output = input.slice(input.length -
                                     pad_length,input.length);
        }
        else
            if((input.length < pad_length) &&
               (pad_type == 'STR_PAD_RIGHT')) {

                var caracteresNecesarios = pad_length-input.length;
                var rellenoEnteros = Math.floor(caracteresNecesarios/pad_string.length);
                var rellenoParte = caracteresNecesarios%pad_string.length;
                var output = input;
                for(var i=0; i<rellenoEnteros; i++) {
                    var output = output + pad_string;
                };
                var output = output + pad_string.slice(0, rellenoParte);
            }
            else
                if((input.length < pad_length) &&
                   (pad_type=='STR_PAD_LEFT')) {

                    var caracteresNecesarios = pad_length-input.length;
                    var rellenoEnteros = Math.floor(caracteresNecesarios/pad_string.length);
                    var rellenoParte = caracteresNecesarios%pad_string.length;
                    var output = "";
                    for(var i=0; i<rellenoEnteros; i++) {
                        var output = output + pad_string;
                    };
                    var output = output + pad_string.slice(0, rellenoParte);
                    var output = output + input;
                }
                else
                    if(input.length == pad_length) {
                        var output = input;
                    };
    return output;
};

The only thing that my function does not do is the STR_PAD_BOTH behavior that I could add with some time and a more comfortable keyboard. You might call the function and test it; bet you'll love it if you don't mind that inner code uses one or two words in Spanish... not big deal I think. I did not added comments for "watermarking" my coding so you can seamless use it in your work nor I compressed the code for enhanced readability. Use it and test it like this and spread the code:

alert("str_pad('murcielago', 20, '123', 'STR_PAD_RIGHT')=" + str_pad('murcielago', 20, '123', 'STR_PAD_RIGHT') + '.');

Upvotes: -2

bugmagnet
bugmagnet

Reputation: 7769

Use:

function zfill(num, len) {
  return(0 > num ? "-" : "") + (Math.pow(10, len) <= Math.abs(num) ? "0" + Math.abs(num) : Math.pow(10, len) + Math.abs(num)).toString().substr(1)
}

This handles negatives and situations where the number is longer than the field width. And floating-point.

Upvotes: 0

broofa
broofa

Reputation: 38151

I often use this construct for doing ad-hoc padding of some value n, known to be a positive, decimal:

(offset + n + '').substr(1);

Where offset is 10^^digits.

E.g., padding to 5 digits, where n = 123:

(1e5 + 123 + '').substr(1); // => 00123

The hexadecimal version of this is slightly more verbose:

(0x100000 + 0x123).toString(16).substr(1); // => 00123

Note 1: I like @profitehlolz's solution as well, which is the string version of this, using slice()'s nifty negative-index feature.

Upvotes: 13

Arthur Barreto
Arthur Barreto

Reputation: 197

Just another solution, but I think it's more legible.

function zeroFill(text, size)
{
  while (text.length < size){
    text = "0" + text;
  }

  return text;
}

Upvotes: 6

lex82
lex82

Reputation: 11317

Use recursion:

function padZero(s, n) {
    s = s.toString(); // In case someone passes a number
    return s.length >= n ? s : padZero('0' + s, n);
}

Upvotes: 3

dtudury
dtudury

Reputation: 639

I was here looking for a standard and had the same idea as Paul and Jonathan... Theirs are super cute, but here's a horrible-cute version:

function zeroPad(n, l, i) {
    return (i = n/Math.pow(10, l))*i > 1 ? '' + n : i.toFixed(l).replace('0.', '');
}

This works too (we're assuming integers, yes?)...

> zeroPad(Math.pow(2, 53), 20);
'00009007199254740992'

> zeroPad(-Math.pow(2, 53), 20);
'-00009007199254740992'

> zeroPad(Math.pow(2, 53), 10);
'9007199254740992'

> zeroPad(-Math.pow(2, 53), 10);
'-9007199254740992'

Upvotes: -1

YellowApple
YellowApple

Reputation: 961

I came up with an absurd one-liner while writing a numeric base converter.

// This is cursed
function p(i,w,z){z=z||0;w=w||8;i+='';var o=i.length%w;return o?[...Array(w-o).fill(z),...i].join(''):i;}

console.log(p(8675309));        // Default: pad w/ 0 to 8 digits
console.log(p(525600, 10));     // Pad to 10 digits
console.log(p(69420, 10, 'X')); // Pad w/ X to 10 digits
console.log(p(8675309, 4));     // Pad to next 4 digits
console.log(p(12345678));       // Don't pad if you ain't gotta pad

Or, in a form that doesn't quite as readily betray that I've sold my soul to the Black Perl:

function pad(input, width, zero) {
    zero = zero || 0; width = width || 8;  // Defaults
    input += '';                           // Convert input to string first

    var overflow = input.length % width    // Do we overflow?
    if (overflow) {                        // Yep!  Let's pad it...
        var needed = width - overflow;     // ...to the next boundary...
        var zeroes = Array(needed);        // ...with an array...
        zeroes = zeroes.fill(zero);        // ...full of our zero character...
        var output = [...zeroes,...input]; // ...and concat those zeroes to input...
        output = output.join('');          // ...and finally stringify.
    } else {
        var output = input;                // We don't overflow; no action needed :)
    }

    return output;                         // Done!
}

One thing that sets this apart from the other answers is that it takes a modulo of the number's length to the target width rather than a simple greater-than check. This is handy if you want to make sure the resulting length is some multiple of a target width (e.g., you need the output to be either 5 or 10 characters long).

I have no idea how well it performs, but hey, at least it's already minified!

Upvotes: 0

Scott Means
Scott Means

Reputation: 655

I think my approach is a little different. The reason I needed to pad a number was to display it in a <pre> element (part of an on-screen log), so it's ultimately going to be a string anyway. Instead of doing any math, I wrote a simple function to overlay a string value on a mask string:

function overlayr(m, s) {
  return m.length > s.length ? m.substr(0, m.length - s.length) + s : s;
}

The benefit of this is that I can use it for all sorts of string alignment tasks. To call it, just pass in the mask and number as a string:

> overlayr('00000', (5).toString())
< "00005"

As an added bonus, it deals with overflows correctly:

> overlayr('00000', (555555).toString())
< "555555"

And of course it's not limited to 0 padding:

> overlayr('*****', (55).toString())
< "***55"

Upvotes: 1

mtizziani
mtizziani

Reputation: 1016

I wrote something in ECMAScript 6 (TypeScript) and perhaps someone can use it:

class Helper {
    /**
     * adds leading 0 and returns string if value is not minSize long,
     * else returns value as string
     *
     * @param {string|number} value
     * @param {number} minSize
     * @returns {string}
     */
    public static leadingNullString(value: string|number, minSize: number): string {
        if (typeof value == "number") {
            value = "" + value;
        }
        let outString: string = '';
        let counter: number = minSize - value.length;
        if (counter > 0) {
            for (let i = 0; i < counter; i++) {
                outString += '0';
            }
        }
        return (outString + value);
    }
}

Helper.leadingNullString(123, 2); returns "123"

Helper.leadingNullString(5, 2); returns "05"

Helper.leadingNullString(40,2); returns "40"

The ecmaScript4 (JavaScript) transpilation looks like that:

var Helper = (function () {
    function Helper() {
    }
    Helper.leadingNullString = function (value, minSize) {
        if (typeof value == "number") {
            value = "" + value;
        }
        var outString = '';
        var counter = minSize - value.length;
        if (counter > 0) {
            for (var i = 0; i < counter; i++) {
                outString += '0';
            }
        }
        return (outString + value);
    };
    return Helper;
}());

Upvotes: 0

AN German
AN German

Reputation: 801

I found the problem interesting, I put my small contribution

function zeroLeftComplete(value, totalCharters = 3) {
    const valueString = value.toString() || '0'
    const zeroLength = valueString.length - totalCharters
    if (Math.sign(parseInt(zeroLength)) === -1) {
        const zeroMissing = Array.from({ length: Math.abs(zeroLength) }, () => '0').join('')
        return `${zeroMissing}${valueString}`
    } else return valueString

};
console.log(zeroLeftComplete(0));
console.log(zeroLeftComplete(1));
console.log(zeroLeftComplete(50));
console.log(zeroLeftComplete(50561,3));

Upvotes: 0

Peter Bailey
Peter Bailey

Reputation: 105914

Since ECMAScript 2017 we have padStart:

const padded = (.1 + "").padStart(6, "0");
console.log(`-${padded}`);

Before ECMAScript 2017

With toLocaleString:

var n=-0.1;
var res = n.toLocaleString('en', {minimumIntegerDigits:4,minimumFractionDigits:2,useGrouping:false});
console.log(res);

Upvotes: 385

Seaux
Seaux

Reputation: 3527

I can't believe all the complex answers on here... Just use this:

var zerofilled = ('0000'+n).slice(-4);

let n = 1
var zerofilled = ('0000'+n).slice(-4);
console.log(zerofilled)

Upvotes: 513

Molimat
Molimat

Reputation: 366

A silly recursive way is:

function paddingZeros(text, limit) {
  if (text.length < limit) {
    return paddingZeros("0" + text, limit);
  } else {
    return text;
  }
}

where the limit is the size you want the string to be.

Ex: appendZeros("7829", 20) // 00000000000000007829

Upvotes: 1

kztd
kztd

Reputation: 3415

Posting in case this is what you are looking for, converts time remaining in milliseconds to a string like 00:04:21

function showTimeRemaining(remain){
  minute = 60 * 1000;
  hour = 60 * minute;
  //
  hrs = Math.floor(remain / hour);
  remain -= hrs * hour;
  mins = Math.floor(remain / minute);
  remain -= mins * minute;
  secs = Math.floor(remain / 1000);
  timeRemaining = hrs.toString().padStart(2, '0') + ":" + mins.toString().padStart(2, '0') + ":" + secs.toString().padStart(2, '0');
  return timeRemaining;
}

Upvotes: 1

air-dex
air-dex

Reputation: 4178

With ES6+ JavaScript:

You can "zerofill a number" with something like the following function:

/**
 * @param number The number
 * @param minLength Minimal length for your string with leading zeroes
 * @return Your formatted string
 */
function zerofill(nb, minLength) {
    // Convert your number to string.
    let nb2Str = nb.toString()

    // Guess the number of zeroes you will have to write.
    let nbZeroes = Math.max(0, minLength - nb2Str.length)

    // Compute your result.
    return `${ '0'.repeat(nbZeroes) }${ nb2Str }`
}

console.log(zerofill(5, 6))    // Displays "000005"

With ES2017+:

/**
 * @param number The number
 * @param minLength Minimal length for your string with leading zeroes
 * @return Your formatted string
 */
const zerofill = (nb, minLength) => nb.toString().padStart(minLength, '0')

console.log(zerofill(5, 6))    // Displays "000005"

Upvotes: 4

Sterling Archer
Sterling Archer

Reputation: 22435

Modern browsers now support padStart, you can simply now do:

string.padStart(maxLength, "0");

Example:

string = "14";
maxLength = 5; // maxLength is the max string length, not max # of fills
res = string.padStart(maxLength, "0");
console.log(res); // prints "00014"

number = 14;
maxLength = 5; // maxLength is the max string length, not max # of fills
res = number.toString().padStart(maxLength, "0");
console.log(res); // prints "00014"

Upvotes: 90

Vasily Hall
Vasily Hall

Reputation: 961

Here's a little trick I think is cool:

(2/10000).toString().split(".")[1]
"0002"
(52/10000).toString().split(".")[1]
"0052"

Upvotes: 0

Mohsen Alyafei
Mohsen Alyafei

Reputation: 5577

The following provides a quick and fast solution:

function numberPadLeft(num , max, padder = "0"){
     return "" == (num += "") ? "" :
     ( dif = max - num.length, dif > 0 ?
     padder.repeat(dif < 0 ? 0 : dif) + num :
     num )
}

Upvotes: 0

Ilja KO
Ilja KO

Reputation: 1616

I didn't see any answer in this form so here my shot with regex and string manipulation

(Works also for negative and decimal numbers)

Code:

function fillZeroes(n = 0, m = 1) {
  const p = Math.max(1, m);
  return String(n).replace(/\d+/, x => '0'.repeat(Math.max(p - x.length, 0)) + x);
}

Some outputs:

console.log(fillZeroes(6, 2))          // >> '06'
console.log(fillZeroes(1.35, 2))       // >> '01.35'
console.log(fillZeroes(-16, 3))        // >> '-016'
console.log(fillZeroes(-1.456, 3))     // >> '-001.456'
console.log(fillZeroes(-456.53453, 6)) // >> '-000456.53453'
console.log(fillZeroes('Agent 7', 3))  // >> 'Agent 007'

Upvotes: 1

chetbox
chetbox

Reputation: 1810

Here's what I used to pad a number up to 7 characters.

("0000000" + number).slice(-7)

This approach will probably suffice for most people.

Edit: If you want to make it more generic you can do this:

("0".repeat(padding) + number).slice(-padding)

Edit 2: Note that since ES2017 you can use String.prototype.padStart:

number.toString().padStart(padding, "0")

Upvotes: 87

Case
Case

Reputation: 4282

A simple elegant solution, where n is the number and l is the length.

function nFill (n, l) {return (l>n.toString().length)?((Array(l).join('0')+n).slice(-l)):n;}

This keeps the length if it is over desired, as not to alter the number.

n = 500;

console.log(nFill(n, 5));
console.log(nFill(n, 2));

function nFill (n, l) {return (l>n.toString().length)?((Array(l).join('0')+n).slice(-l)):n;}

Upvotes: 0

suleman
suleman

Reputation: 66

I used

Utilities.formatString("%04d", iThe_TWO_to_FOUR_DIGIT) 

which gives up to 4 leading 0s

NOTE: THIS REQUIRES Google's apps-script Utilities:

https://developers.google.com/apps-script/reference/utilities/utilities#formatstringtemplate-args

Upvotes: -1

profitehlolz
profitehlolz

Reputation: 640

Simple way. You could add string multiplication for the pad and turn it into a function.

var pad = "000000";
var n = '5';
var result = (pad+n).slice(-pad.length);

As a function,

function paddy(num, padlen, padchar) {
    var pad_char = typeof padchar !== 'undefined' ? padchar : '0';
    var pad = new Array(1 + padlen).join(pad_char);
    return (pad + num).slice(-pad.length);
}
var fu = paddy(14, 5); // 00014
var bar = paddy(2, 4, '#'); // ###2

Upvotes: 345

Stephen Quan
Stephen Quan

Reputation: 26354

I didn't see anyone point out the fact that when you use String.prototype.substr() with a negative number it counts from the right.

A one liner solution to the OP's question, a 6-digit zerofilled representation of the number 5, is:

console.log(("00000000" + 5).substr(-6));

Generalizing we'll get:

function pad(num, len) { return ("00000000" + num).substr(-len) };

console.log(pad(5, 6));
console.log(pad(45, 6));
console.log(pad(345, 6));
console.log(pad(2345, 6));
console.log(pad(12345, 6));

Upvotes: 8

Related Questions