jquery 0 in front of the number specified length

Source: Internet
Author: User

In the work, if we output the number of the length is fixed, the assumption is 4, if the number is 3, then output 0003, not enough digits in front of the complement of 0, here summed up to provide three different ways to achieve the number of JS code to fill 0 of the operation;

The first: the most original way of writing

function pad (num, n) { 
var i = (num + ""). Length; 
while (i++ < n) num = "0" + num; 
return num; 
}

The second: the method of

function Prefixinteger (num, length) {return
  (Num/math.pow (10,length)). toFixed (length). substr (2);
}
Third: Methods (more efficient)

function Prefixinteger (num, length) {return
 ("0000000000000000" + num). substr (-length);
Fourth: Methods (more efficient, concise)

function Prefixinteger (num, length) {return
 (Array (length). Join (' 0 ') + num). Slice (-length);
}
Fifth: Method (Magic Recursive method)

/* Magic recursive */ 
function pad2 (num, n) { 
if ((num + ""). Length >= N) return num; 
return Pad2 ("0" + num, n); 
}


Article reprint

JavaScript Digital 0 Tip: How to make a number in front of a specified length of 0

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.