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