Most of the time, in order to display the format, the first 0 must be performed if a character string is not in the correct position. The following article mainly introduces several methods for adding a front 0 (Zero Filling) in javascript. The article provides detailed sample code. For more information, see the following. Preface
As we all know, numbers in JavaScript do not have a front 0, so we need to perform our own operations to add a front 0 and convert it to a string.
If we generate a four-digit data with a forward value of 0, we can think of the following method:
function addPreZero(num){ if(num<10){ return '000'+num; }else if(num<100){ return '00'+num; }else if(num<1000){ return '0'+num; }else{ return num; }}
The idea of this method is relatively simple. The number of digits in the current data can be used to add the number of leading zeros. However, such an algorithm is difficult to write. If a large number of leading zeros are required, so you have to write a lot of if... else.
Based on this idea, we can first calculate the number of digits and then directly add the corresponding 0 digits:
function addPreZero(num){ var t = (num+'').length, s = ''; for(var i=0; i<4-t; i++){ s += '0'; } return s+num;}
The implementation of this method is to calculate all the leading zeros based on the number of digits of the current num, and then concatenate num.
On this basis, we can also consider this: for example, if we need a total of 10 data records with a forward value of 0, we first add 9 forward values regardless of the number of digits, then, extract the last 10 digits of the string and obtain the required data:
function addPreZero(num){ return ('000000000'+num).slice(-10);}
Summary
The above is all the content of this article. We should try to come up with more methods to achieve the desired results. On the one hand, we can expand our thinking, on the other hand, we can also choose a better way. I hope the content of this article will help you in your study or work. If you have any questions, you can leave a message.
For more articles about how to add a front-end 0 (zero-padding) in javascript, refer to PHP!