Results 1 to 2 of 2

Thread: Write number right justified with leading zeroes?

  1. #1
    Join Date
    Oct 2013

    Write number right justified with leading zeroes?

    Assume a variable "mynum" contains a number 333.

    Now I want to output this number right-justified with leading zeroes so that the width of the number is (minimum) 5.

    It should look like:


    If the variable contains a number with more than 5 digits then the full number should be output e.g.

    1234567 ---> 1234567

    How can I achieve this?


  2. #2
    Join Date
    Mar 2007
    Couple of prototypes for you...
    String.prototype.repeat = function( f ){
    	var t = "", f = f || 1;
    	while( f-- > 0 ) t+=this;
    	return t;
    Number.prototype.pad = function(p){
    	var p=p||2;
    	var p = (l=(""+this).length) > p ? l : p;
    	return ("0".repeat(p)+this).slice(-(p) );
    var n = 1234;
    var x = n.pad(8);
    console.log("The number %d is padded to %d places and looks like %s",n,8,x)
    will output The number 1234 is padded to 8 places and looks like 00001234 in the console (F12 open / clode, click on log to see)
    Last edited by \\.\; 08-10-2017 at 07:21 AM.
    --> JavaScript Frameworks like JQuery, Angular, Node <--
    ... and please remember to wrap code with forum BBCode tags:-

    [CODE]...[/CODE] [HTML]...[/HTML] [PHP]...[/PHP]

    If you can't think outside the box, you will be trapped forever with no escape...

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center