JavaScript format number to day with always 3 digits [duplicate]
Asked Answered
S

6

15

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!

Snazzy answered 31/5, 2012 at 21:50 Comment(2)
You might check the answers here: #610906Vaillancourt
only correct answer is String(<yourNumber>).padStart(3,0) but as this is closed I can't really answer thisIntensive
S
38

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);
}
Subsequence answered 31/5, 2012 at 21:54 Comment(8)
The first won't work for numbers with 4 digits and more.Allergist
@VisioN: The title says "always 3 digits"Soma
...though the negative index will fail in IE8 and lower.Soma
@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.Allergist
@VisioN: fair enough, post updated.Subsequence
Nice but use substring rather than substr which is deprecated.Flocculate
@Flocculate substring does not support negative indexing ( link ). Best to use slice() instead.Olds
@Flocculate using substring doesn't allow negative value in the parameters. when given negative values it takes the value as 0. I'm using substr as of now, its working!!Rosalie
Z
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"

Zygophyllaceous answered 31/5, 2012 at 21:57 Comment(0)
S
5

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.

Soma answered 31/5, 2012 at 21:54 Comment(0)
I
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

Inert answered 31/5, 2012 at 21:52 Comment(0)
A
1

One possible solution:

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

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

Allergist answered 31/5, 2012 at 21:53 Comment(0)
R
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;
};
Rhodic answered 31/5, 2012 at 21:55 Comment(1)
I think you meant .join("0") and I think you meant to put that before the str.Cl

© 2022 - 2024 — McMap. All rights reserved.