Adding extra zeros in front of a number using jQuery?

I have file that are uploaded which are formatted like so

MR 1

MR 2

MR 100

MR 200

MR 300

ETC.

What i need to do is add extra two 00s before anything before MR 10 and add one extra 0 before MR10-99

So files are formatted

MR 001

MR 010

MR 076

ETC.

Any help would be great!


Solution 1:

Assuming you have those values stored in some strings, try this:

function pad (str, max) {
  str = str.toString();
  return str.length < max ? pad("0" + str, max) : str;
}

pad("3", 3);    // => "003"
pad("123", 3);  // => "123"
pad("1234", 3); // => "1234"

var test = "MR 2";
var parts = test.split(" ");
parts[1] = pad(parts[1], 3);
parts.join(" "); // => "MR 002"

Solution 2:

I have a potential solution which I guess is relevent, I posted about it here:

https://www.facebook.com/antimatterstudios/posts/10150752380719364

basically, you want a minimum length of 2 or 3, you can adjust how many 0's you put in this piece of code

var d = new Date();
var h = ("0"+d.getHours()).slice(-2);
var m = ("0"+d.getMinutes()).slice(-2);
var s = ("0"+d.getSeconds()).slice(-2);

I knew I would always get a single integer as a minimum (cause hour 1, hour 2) etc, but if you can't be sure of getting anything but an empty string, you can just do "000"+d.getHours() to make sure you get the minimum.

then you want 3 numbers? just use -3 instead of -2 in my code, I'm just writing this because I wanted to construct a 24 hour clock in a super easy fashion.

Solution 3:

Note: see Update 2 if you are using latest ECMAScript...


Here a solution I liked for its simplicity from an answer to a similar question:

var n = 123

String('00000' + n).slice(-5); // returns 00123
('00000' + n).slice(-5);       // returns 00123

UPDATE

As @RWC suggested you can wrap this of course nicely in a generic function like this:

function leftPad(value, length) { 
    return ('0'.repeat(length) + value).slice(-length); 
}

leftPad(123, 5); // returns 00123

And for those who don't like the slice:

function leftPad(value, length) {
    value = String(value);
    length = length - value.length;
    return ('0'.repeat(length) + value)
}

But if performance matters I recommend reading through the linked answer before choosing one of the solutions suggested.

UPDATE 2

In ES6 the String class now comes with a inbuilt padStart method which adds leading characters to a string. Check MDN here for reference on String.prototype.padStart(). And there is also a padEnd method for ending characters.

So with ES6 it became as simple as:

var n = 123;
n.padStart(5, '0'); // returns 00123

Solution 4:

function addLeadingZeros (n, length)
{
    var str = (n > 0 ? n : -n) + "";
    var zeros = "";
    for (var i = length - str.length; i > 0; i--)
        zeros += "0";
    zeros += str;
    return n >= 0 ? zeros : "-" + zeros;
}

//addLeadingZeros (1, 3) =   "001"
//addLeadingZeros (12, 3) =  "012"
//addLeadingZeros (123, 3) = "123"

Solution 5:

This is the function that I generally use in my code to prepend zeros to a number or string.

The inputs are the string or number (str), and the desired length of the output (len).

var PrependZeros = function (str, len) {
    if(typeof str === 'number' || Number(str)){
    str = str.toString();
    return (len - str.length > 0) ? new Array(len + 1 - str.length).join('0') + str: str;
}
else{
    for(var i = 0,spl = str.split(' '); i < spl.length; spl[i] = (Number(spl[i])&& spl[i].length < len)?PrependZeros(spl[i],len):spl[i],str = (i == spl.length -1)?spl.join(' '):str,i++);
    return str;
}

};

Examples:

PrependZeros('MR 3',3);    // MR 003
PrependZeros('MR 23',3);   // MR 023
PrependZeros('MR 123',3);  // MR 123
PrependZeros('foo bar 23',3);  // foo bar 023