JavaScript implements a method to add zero before the number according to the specified length _ javascript skills

Source: Internet
Author: User
This article mainly introduces how to implement zero-padding output based on the specified length of a number in JavaScript. The example shows how to perform a number-padding operation in javascript, if you need it, refer to the example in this article to describe how to add zero output before a number based on 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.

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.