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.