Adding extra zeros in front of a number using jQuery?

Javascript

Javascript Problem Overview


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!

Javascript Solutions


Solution 1 - Javascript

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

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

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

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

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

Solution 6 - Javascript

If you split on the space, you can add leading zeros using a simple function like:

function addZeros(n) {
  return (n < 10)? '00' + n : (n < 100)? '0' + n : '' + n;
}

So you can test the length of the string and if it's less than 6, split on the space, add zeros to the number, then join it back together.

Or as a regular expression:

function addZeros(s) {
  return s.replace(/ (\d$)/,' 00$1').replace(/ (\d\d)$/,' 0$1');
}

I'm sure someone can do it with one replace, not two.

Edit - examples
alert(addZeros('MR 3'));    // MR 003
alert(addZeros('MR 23'));   // MR 023
alert(addZeros('MR 123'));  // MR 123
alert(addZeros('foo bar 23'));  // foo bar 023

It will put one or two zeros infront of a number at the end of a string with a space in front of it. It doesn't care what bit before the space is.

Solution 7 - Javascript

Just for a laugh do it the long nasty way....:
(NOTE: ive not used this, and i would not advise using this.!)

function pad(str, new_length) {
    ('00000000000000000000000000000000000000000000000000' + str).
    substr((50 + str.toString().length) - new_length, new_length)
}

    

Solution 8 - Javascript

I needed something like this myself the other day, Pud instead of always a 0, I wanted to be able to tell it what I wanted padded ing the front. Here's what I came up with for code:

function lpad(n, e, d) {
  var o = ''; if(typeof(d) === 'undefined'){ d='0'; } if(typeof(e) === 'undefined'){ e=2; }
  if(n.length < e){ for(var r=0; r < e - n.length; r++){ o += d; } o += n; } else { o=n; }
  return o; }

Where n is what you want padded, e is the power you want it padded to (number of characters long it should be), and d is what you want it to be padded with. Seems to work well for what I needed it for, but it would fail if "d" was more than one character long is some cases.

Solution 9 - Javascript

var str = "43215"; 
console.log("Before : \n string :"+str+"\n Length :"+str.length);
var max = 9;
while(str.length < max ){
                                str = "0" + str;
 
                        }
console.log("After : \n string :"+str+"\n Length :"+str.length);

It worked for me ! To increase the zeroes, update the 'max' variable

Working Fiddle URL : Adding extra zeros in front of a number using jQuery?:

Solution 10 - Javascript

> str could be a number or a string.

formatting("hi",3);
function formatting(str,len)
{
   return ("000000"+str).slice(-len);
}

Add more zeros if needs large digits

Solution 11 - Javascript

In simple terms we can written as follows,

for(var i=1;i<=31;i++)
    i=(i<10) ? '0'+i : i;

//Because most of the time we need this for day, month or amount matters.

Solution 12 - Javascript

Know this is an old post, but here's another short, effective way: zeros

edit: dur. if num isn't string, you'd add:

len -= String(num).length;

else, it's all good

function addLeadingZeros(sNum, len) {
    len -= sNum.length;
    while (len--) sNum = '0' + sNum;
    return sNum;
}

Solution 13 - Javascript

Try following, which will convert convert single and double digit numbers to 3 digit numbers by prefixing zeros.

var base_number = 2;
var zero_prefixed_string = ("000" + base_number).slice(-3);

Solution 14 - Javascript

By adding 100 to the number, then run a substring function from index 1 to the last position in right.

var dt = new Date();
var month = (100 + dt.getMonth()+1).toString().substr(1, 2);
var day = (100 + dt.getDate()).toString().substr(1, 2);

console.log(month,day);

you will got this result from the date of 2020-11-3

11,03

I hope the answer is useful

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChill Web DesignsView Question on Stackoverflow
Solution 1 - JavascriptTodd YandellView Answer on Stackoverflow
Solution 2 - JavascriptChristopher ThomasView Answer on Stackoverflow
Solution 3 - JavascriptWiltView Answer on Stackoverflow
Solution 4 - JavascriptMadBenderView Answer on Stackoverflow
Solution 5 - JavascriptDavan EtelamakiView Answer on Stackoverflow
Solution 6 - JavascriptRobGView Answer on Stackoverflow
Solution 7 - Javascriptuser2992783View Answer on Stackoverflow
Solution 8 - JavascriptShoeMakerView Answer on Stackoverflow
Solution 9 - JavascriptKarthikeyan BaskaranView Answer on Stackoverflow
Solution 10 - JavascriptAmal KalutotageView Answer on Stackoverflow
Solution 11 - JavascriptRamasamy KasiView Answer on Stackoverflow
Solution 12 - JavascriptToddView Answer on Stackoverflow
Solution 13 - Javascriptvivek shirodkarView Answer on Stackoverflow
Solution 14 - JavascriptHamid JolanyView Answer on Stackoverflow