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

JavaScript implements a method of padding zeros in front of numbers according to a specified length and outputting them_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:08:321119browse

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.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn