---
title: "JS数字指定长度不足前补零的实现"
author: "wsj123"
date: "2018-03-10T10:25:58Z"
tags: ["JavaScript"]
categories: ["Web前端"]
slug: "js"
draft: false
lastmod: "2018-03-10T10:24:41Z"
id: 2412696
url: "https://wsj123.iteye.com/blog/2412696"
---

JS数字指定长度不足前补零的实现
**问题描述：**
        要求输出的数字长度是固定的，如长度为2，数字为1，则输出01，即不够位数就在之前补足0。
**解决方法：**
方法1

```javascript
function fn1(num, length) {
    return (num/Math.pow(10,length)).toFixed(length).substr(2);
}
```

方法2

```javascript
function fn2(num, length) {
    return ( "0000000000000000" + num ).substr( -length );
}
```

方法3

```javascript
function fn3(num, length) {
    return (Array(length).join('0') + num).slice(-length);
}
```

上述三种方法的效率如下：

```javascript
console.time('time1');
fn1();
console.timeEnd('time1');//chrome返回值：time1: 0.126953125ms
```



```javascript
console.time('time2');
fn2();
console.timeEnd('time2'); //chrome返回值：time2: 0.0810546875ms
```



```javascript
console.time('3');
fn3();
console.timeEnd('time3'); //chrome返回值：time3: 0ms
```