JavaScript implements the method to add Zero output before the number according to the specified length, javascript Length

Source: Internet
Author: User

JavaScript implements the method to add Zero output before the number according to the specified length, javascript Length

This example describes how to add Zero output before the specified length in JavaScript. Share it with you for your reference. The specific analysis is as follows:

For example, we want the length of the number to be output to be fixed. Suppose it is 10. If the number is 123, it will output 0000000123. If the number is not enough, it will make up 0, three different methods are provided to implement the JS Code to add 0 to the number.

Method 1

Function PrefixInteger (num, length) {return (num/Math. pow (10, length). toFixed (length). substr (2 );}

Method 2, more efficient

Function PrefixInteger (num, length) {return ("0000000000000000" + num). substr (-length );}

More efficient

Function PrefixInteger (num, length) {return (Array (length). join ('0') + num). slice (-length );}

I hope this article will help you design javascript programs.

Related Article

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.