JavaScript implements the method of zeroing out a number at a specified length
- 2020-05-17 04:46:18
- OfStack
The example in this article describes how JavaScript implements zeroing output in front of a number at a specified length. Share with you for your reference. The specific analysis is as follows:
For example, we want the length of the number output to be fixed, let's say 10. If the number is 123, then 0000000123 will be output, and the insufficient number will complement 0 before. Here, we provide three different ways to implement the operation of 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 );
}
There are more efficient ones
function PrefixInteger(num, length) {
return (Array(length).join('0') + num).slice(-length);
}
I hope this article is helpful for you to design javascript program.