Home > Web Front-end > JS Tutorial > body text

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

WBOY
Release: 2016-05-16 16:08:32
Original
1084 people have browsed it

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);
}
Copy after login

Method 2, more efficient

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

There are more efficient ones

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

I hope this article will be helpful to everyone’s JavaScript programming design.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!