16

Possible Duplicate:
How can I create a Zerofilled value using JavaScript?

I have to output a day number that must always have 3 digits. Instead of 3 it must write 003, instead of 12 it must write 012. If it is greater than 100 output it without formatting. I wonder if there's a regex that I could use or some quick in-line script, or I must create a function that should do that and return the result. Thanks!

Community
  • 1
  • 1
ali
  • 10,927
  • 20
  • 89
  • 138
  • You might check the answers here: http://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format – Jonathan M May 31 '12 at 21:51

6 Answers6

37

How about:

 zeroFilled = ('000' + x).substr(-3)

For arbitrary width:

 zeroFilled = (new Array(width).join('0') + x).substr(-width)

As per comments, this seems more accurate:

lpad = function(s, width, char) {
    return (s.length >= width) ? s : (new Array(width).join(char) + s).slice(-width);
}
georg
  • 211,518
  • 52
  • 313
  • 390
  • The first won't work for numbers with 4 digits and more. – VisioN May 31 '12 at 21:57
  • @VisioN: The title says *"always 3 digits"* –  May 31 '12 at 21:58
  • 1
    ...though the negative index will fail in IE8 and lower. –  May 31 '12 at 22:00
  • @amnotiam Right, but there is also another phrase which can be considered differently: *If it is greater than 100 output it without formatting*. Who knows where is the right way, it's good to play safe. – VisioN May 31 '12 at 22:02
  • @VisioN: fair enough, post updated. – georg May 31 '12 at 22:03
  • Nice but use substring rather than substr which is deprecated. – andreszs Feb 20 '20 at 14:56
  • @andreszs substring does not support negative indexing ( [link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring#differences_between_substring_and_slice) ). Best to use `slice()` instead. – Will Blair Mar 25 '22 at 05:47
6

I found an elegant solution by Samuel Mullen on his blog. I simply optimized the zeroes creation.

function lpad(value, padding) {
    var zeroes = new Array(padding+1).join("0");
    return (zeroes + value).slice(-padding);
}

Usage: lpad(12, 3) results in "012"

Mattias Buelens
  • 19,609
  • 4
  • 45
  • 51
4

You can do this...

("00" + day).slice(-3)

It'll prepend the zeros, and then .slice() will always give you the last 3 values of the string.

1

Here is a simple function that pads a number with zeroes to a certain width:

function zeroFill(number, width) {
    width -= number.toString().length;
    if(width > 0) {
        return new Array(width + (/\./.test(number) ? 2 : 1)).join('0') + number;
    }
    return number + ""; // always return a string
}

(from How can I pad a value with leading zeros?)

Since the original answer did not explain how the function works I'll do it here.

width initially contains the total length you want, so width - number_of_digits is the number of padding chars necessary.
new Array(len + 1).join(str) repeats str len times.
The regex is used to add an additional padding zero in case of a number containing a decimal point since the point was also included in the number_of_digits determined using number.toString().length

Community
  • 1
  • 1
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
1

One possible solution:

​while ((val+"").length < 3​) {
    val = "0" + val;
}

DEMO: http://jsfiddle.net/WfXVn/

VisioN
  • 143,310
  • 32
  • 282
  • 281
1

I would write the following function:

var pad = function(n, length) {
    var str = "" + n;
    if(str.length < length) str = new Array(length - str.length).join("0") + str;
    return str;
};
Samuel Rossille
  • 18,940
  • 18
  • 62
  • 90