When dealing with JavaScript, the need often arises to pad a number with leading zeros. For instance, the number 9 becomes "0009," and 10 becomes "0010," always adhering to a four-digit format.
A straightforward approach involves subtracting the number from 4 to determine the necessary number of zeros. While functional, it lacks flair.
In ES2017, the String.prototype.padStart() method offers a more elegant solution. It appends the specified character (by default, a space) to the left of the string until it reaches the desired length.
n = 9; String(n).padStart(4, '0'); // '0009' n = 10; String(n).padStart(4, '0'); // '0010'
In scenarios where padStart() may not be an option, a generic padding function can be utilized:
function pad(n, width, z) { z = z || '0'; n = n + ''; return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n; }
This function employs an array's ability to accept a number as an argument and create an array with that length, populated with undefined elements. When joining these elements with a zero (or other specified character), a string is generated with the appropriate number of leading zeros.
pad(10, 4); // 0010 pad(9, 4); // 0009 pad(123, 4); // 0123 pad(10, 4, '-'); // --10
The above is the detailed content of How Can I Pad a Number with Leading Zeros in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!