Friday, September 28, 2007
Padding zero in Javascript
To display a number x in 2 digits with padding zero in the front, here's the snippet to do so:
String("0" + x).slice(-2);
To display 5 digits with padding zeros, it'll be:
String("0000" + x).slice(-5);
The number of zero can be parameterized, of course:
var padding_zero = function(x, n) {
var zeros = repeat("0", n);
return String(zeros + x).slice(-1 * n)
}
The function repeat is the string repeater defined in here.
But these definitions doesn't check the original number if it's longer then n digits. Calling padding_zero(357, 2) will give you 57. Neither does it check if its parameters are numbers or not. (Easy and may not be a big issue depends on what you want.)
And of course, you can pad something other than zero. For example, you can pad up to 5 number of
before
. They are just two different img strings anyway:
// pad up to n Ys before X.
var pad = function(x, n, y) {
var zeros = repeat(y, n);
return String(zeros + x).slice(-1 * n);
}
So the code to generate a line of 5 rating stars may just looks like:
pad("111", 5, "0).replace(/1/g, star_img).replace(/0/g, empty_star_img);
The idea here is to generate something like "11100" first, then replace them with img tags.
All these functions assumes x,y variables are only one character to work properly because I use slice() function on String classes. To make it more general, should probably use Array.
Labels: format, javascript, number, string
Subscribe to Posts [Atom]
