Home >Web Front-end >JS Tutorial >JavaScript implements a method of padding zeros in front of numbers according to a specified length and outputting them_javascript skills
The example in this article describes the JavaScript method of padding zeros in front of a number according to the specified length and outputting it. Share it with everyone for your reference. The specific analysis is as follows:
For example, we hope that the length of the output number is fixed, assuming it is 10. If the number is 123, then 0000000123 will be output. If there are not enough digits, 0 will be added before. Here are three different ways to implement JS code to add numbers. 0 actions
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 will be helpful to everyone’s JavaScript programming design.