JavaScript implementation of zero padding in front of the digital output according to the specified length

This article describes the method of example implemented in JavaScript specified length to a digital output with leading zeros. Share to you for your reference. Specific analysis is as follows:

For example, we want the digital output is a fixed length, is assumed to be 10, if the number is 123, the output 0000000123, not enough number of bits make up just before 0, here are three different ways to implement the digital up operation JS code 0

method 1:

function PrefixInteger(num, length) {
  return (num/Math.pow(10,length)).toFixed(length).substr(2);
}

Method 2 is more efficient:

function PrefixInteger(num, length) {
 return ( "0000000000000000" + num ).substr( -length );
}

There are even more efficient:

function PrefixInteger(num, length) {
 return (Array(length).join('0') + num).slice(-length);
}

In this paper, we hope the the javascript programming help.

Reprinted: https://www.jb51.net/article/62499.htm

Guess you like

Origin www.cnblogs.com/taohuaya/p/11265691.html