Leading Zeros in JavaScript Numbers
In JavaScript, is there a way to automatically add leading zeros to numbers to achieve a specific string length? For instance, converting 5 to "05" with a target length of 2?
Solution:
Conversion to String
Since numbers inherently don't have leading zeros, we need to convert the number to a string first. Here's a sample function:
function pad(num, size) { num = num.toString(); while (num.length < size) { num = "0" + num; } return num; }
Example:
pad(5, 2); // "05"
Alternative Approach
If the maximum number of leading zeros is known, an alternative method can be more efficient:
function pad(num, size) { var s = "000000000" + num; return s.substr(s.length - size); }
Negative Numbers
Handling negative numbers requires stripping the negative sign and re-adding it after padding:
function padWithSign(num, size) { if (num < 0) { num = -num; return "-" + pad(num, size); } else { return pad(num, size); } }
The above is the detailed content of How to Add Leading Zeros to Numbers in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!