Prepending Leading Zeros to Numbers in JavaScript
Is there a way to add leading zeros to numbers in order to obtain a string with a consistent length? For instance, the number 5 should be converted to "05" if two digits are specified.
Solution:
To add leading zeros, you need to convert the number into a string because numbers don't recognize leading zeros. Here's one way to achieve this:
function pad(num, size) { num = num.toString(); while (num.length < size) num = "0" + num; return num; }
For example, if you want to add two leading zeros to the number 5:
pad(5, 2); // returns "05"
However, this function assumes that you'll never need more than 10 leading zeros. If you anticipate larger values, you can use a different approach:
function pad(num, size) { var s = "000000000" + num; return s.substr(s.length - size); }
For example:
pad(5, 6); // returns "000005"
Note that if you need to handle negative numbers, you'll need to remove and re-add the negative sign after padding.
The above is the detailed content of How Can I Add Leading Zeros to Numbers in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!