Home >Web Front-end >JS Tutorial >Several ways to add leading 0 (zero padding) in javascript

Several ways to add leading 0 (zero padding) in javascript

高洛峰
高洛峰Original
2017-01-07 16:21:143850browse

Preface

As we all know, numbers in JavaScript do not have leading 0s, so we need to do our own operations to add leading 0s, and we have to convert them into strings.

If a data with a total of 4 digits and leading 0s is generated, the method we can usually think of is like this:

function addPreZero(num){
 if(num<10){
  return &#39;000&#39;+num;
 }else if(num<100){
  return &#39;00&#39;+num;
 }else if(num<1000){
  return &#39;0&#39;+num;
 }else{
  return num;
 }
}

The idea of ​​​​this method is relatively simple. According to the current The number of digits in the data is used to supplement the corresponding number of leading 0s; however, this algorithm is more troublesome to write. If a lot of leading 0s are required, a lot of if...else must be written.

Still based on this idea, we can first calculate how many digits this number has, and then directly add the corresponding 0:

function addPreZero(num){
 var t = (num+&#39;&#39;).length,
  s = &#39;&#39;;
  
 for(var i=0; i<4-t; i++){
  s += &#39;0&#39;;
 }
  
 return s+num;
}

The implementation of this method is based on the current num number of digits to calculate all leading 0s, and then concatenate num.

On this basis, we can also think about it this way: For example, if we need a total of 10 digits of data with leading 0s, then first, no matter how many digits the current number is, add 9 digits first. Prefix 0, and then intercept the last 10 digits of this string, then you will get the required data:

function addPreZero(num){
 return (&#39;000000000&#39;+num).slice(-10);
}

Summary

The above is the entire content of this article, to realize your dream There are many methods that require results, and we should try to come up with as many methods as possible. On the one hand, it can expand our thinking, and on the other hand, it can also allow us to choose better methods. I hope the content of this article can be of some help to everyone's study or work. If you have any questions, you can leave a message to communicate.

For more related articles on several methods of adding leading 0 (zero padding) to javascript, please pay attention to the PHP Chinese website!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn