Home >Web Front-end >JS Tutorial >How to Pad a Number with Leading Zeros in JavaScript?
How to Pad a Number with Leading Zeros in JavaScript
JavaScript lacks a built-in function for padding numbers with leading zeros. However, you can achieve this padding using various methods.
Solution 1: Using String.prototype.padStart()
For ES2017 and above, you can leverage the String.prototype.padStart() method:
String(n).padStart(4, '0');
This will pad the number n with zeros until it reaches a total length of 4. For example:
n = 9; String(n).padStart(4, '0'); // '0009' n = 10; String(n).padStart(4, '0'); // '0010'
Solution 2: Using Array.prototype.join()
For pre-ES2017 browsers, you can use a combination of Array.prototype.join() and string concatenation:
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 first checks if the number's string length is already greater than or equal to the desired width. If not, it initializes an array with a length equal to the width minus the number's current length plus 1 and joins it with the zero character. This effectively creates a string of zeros of the appropriate length, which is then concatenated with the number.
Example Usage:
pad(10, 4); // 0010 pad(9, 4); // 0009 pad(123, 4); // 0123 pad(10, 4, '-'); // --10
The above is the detailed content of How to Pad a Number with Leading Zeros in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!