7

I need your help.

I'd like to create a function that would add some zeros in front of a number. The maximum numbers of digits that the total string should have is 6. Here are examples:

     9 -> 000009
    14 -> 000014
   230 -> 000230
  1459 -> 001459
 21055 -> 021055
987632 -> 987632 (Do nothing, there's already 6 digits)
3
  • 1
    Good luck! Let us know when you've tried something and have some specific bug you need help with. Commented May 27, 2015 at 19:01
  • Please show what you have tried so far. Commented May 27, 2015 at 19:02
  • possible duplicate of How can I create a Zerofilled value using JavaScript? Commented Jun 23, 2015 at 20:58

8 Answers 8

13

A simple one line solution without any loops

Works with IE5-11, Firefox, Chrome, etc. Assumes integer input.

 function pad(n) { return ("000000" + n).slice(-6); }

Run snippet to test:

<html>
<body>
<input id="stdin" placeholder="enter a number" maxlength="6"><button onclick="test()">Test</button>
<textarea id="stdout" style="width:100%;height:20em;padding:1em;"></textarea>
<script type="text/javascript">
    
   function pad(n) { return ("000000" + n).slice(-6); }
    
   function test() {
       var n = parseInt( document.getElementById('stdin').value);
       var e = document.getElementById('stdout').innerHTML += n + ' = ' + pad(n) + '\n';
   }
 
</script>
</body>
</html>

Sign up to request clarification or add additional context in comments.

2 Comments

And if you want to be able to define the length of padding dynamically: function pad(n, len) { return ((new Array(len + 1).join('0')) + n).slice(-len); }
A significantly more performant way to allow for dynamically declaring length: function pad(n, str) { return (str + n).slice(-str.length); } Usage: pad(number, '000000'); By passing a static string you get the performance boost (JSPerf) from not dynamically creating the string on each invocation. Bonus: You get the added benefit of being able to pass in any string: pad(number, '######');
5

The following will add a zero to the string of numbers until the length is equal to 6.

var s = '9876'
while(s.length < 6){
  s = '0' + s
}
alert(s)

Comments

3

One more . . . this one works with:

  1. strings and numbers,
  2. handles variable lengths, and
  3. lets you chose the padding character

Code:

function padZerosToLength (value, minLength, padChar) {
    var iValLength= value.toString().length;
    return ((new Array((minLength + 1) - iValLength).join(padChar)) + value);
}

Here are some sample results with varying input:

padZerosToLength(1, 6, 0);       ===>  000001
padZerosToLength(12, 6, 0);      ===>  000012
padZerosToLength(123, 6, 0);     ===>  000123
padZerosToLength(1234, 6, 0);    ===>  001234
padZerosToLength(12345, 6, 0);   ===>  012345
padZerosToLength(123456, 6, 0);  ===>  123456

. . . with varying length:

padZerosToLength(1, 1, 0);  ===>  1
padZerosToLength(1, 2, 0);  ===>  01
padZerosToLength(1, 3, 0);  ===>  001
padZerosToLength(1, 4, 0);  ===>  0001
padZerosToLength(1, 5, 0);  ===>  00001
padZerosToLength(1, 6, 0);  ===>  000001

. . . and with varying padding character:

padZerosToLength(1, 6, 0);         ===>  000001
padZerosToLength(1, 6, 1);         ===>  111111
padZerosToLength(1, 6, "x");       ===>  xxxxx1
padZerosToLength(1, 6, ".");       ===>  .....1
padZerosToLength(1, 6, " ");       ===>       1
padZerosToLength(1, 6, "\u25CF");  ===>  ●●●●●1

Comments

1

You will need to convert the number to a string. Then I would split that string to an array and then add '0' to the front of that array until the length is 6. Then join. Check out this repl or see the code below: http://repl.it/piT

var num = 14;
var lengthOfNum = 6;
var numString = num.toString();
var numArray = numString.split('');
var returnString = '';

while (numArray.length < 6) {
    numArray.unshift('0');
}

returnString = numArray.join('');

Comments

0

Recursive solution just for the heck of it:

function padNumberString(numberString) {
    if (numberString.length >= 6) {
        return numberString;
    }
    return padNumberString('0' + numberString);
}

Comments

0

String.prototype.padStart()

padStart(targetLength)
padStart(targetLength, padString)
'123'.padStart(5, "0");     // "00123"

For more detail you could look at developer.mozilla --> String.prototype.padStart()

Comments

-1

A simple solution would be

    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 (9, 3) =   "009"
//addLeadingZeros (15, 3) =  "015"
//addLeadingZeros (333, 3) = "333"

2 Comments

Is this Java? This question is tagged JavaScript.
man..I didnt see this, am selected .net tag this question qppeared
-2

I have been using the SugarJs API for a long time and their padding feature works great.

http://sugarjs.com/api/Number/pad

(9).pad(6, true) --> 000009
(14).pad(6, true) --> 000014

etc...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.