Padding Numbers with Leading Zeros in JavaScript
Original Question:
Can JavaScript be used to pad a number with leading zeros to a specified width? For example, a number like 9 should be padded to "0009" with three leading zeros.
Solution:
ES2017 Update:
String.prototype.padStart(): This built-in method allows padding a string with a specified number of characters at the beginning:
n = 9; String(n).padStart(4, '0'); // '0009'
Legacy Approach:
Custom Function: If ES2017 features are not available, a custom function can be created to pad the number:
function pad(n, width, z) { z = z || '0'; n = n + ''; return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n; }
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 Can I Pad Numbers with Leading Zeros in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!