JavaScript implements the method of adding zero before the number according to the specified length
This article mainly introduces how to implement zero-padding output in front of a number based on the specified length in JavaScript. The example shows how to use javascript to perform zero-padding. For more information, see
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
?
1 2 3 |
Function PrefixInteger (num, length ){ Return (num/Math. pow (10, length). toFixed (length). substr (2 ); } |
Method 2, more efficient
?
1 2 3 |
Function PrefixInteger (num, length ){ Return ("0000000000000000" + num). substr (-length ); } |
More efficient
?
1 2 3 |
Function PrefixInteger (num, length ){ Return (Array (length). join ('0') + num). slice (-length ); } |
I hope this article will help you design javascript programs.