JS 数字补零的几种方法

Posted by Dan on May 12, 2018

本文介绍几种补零的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// 简单的for 循环补零

function addPrefix1 (num, length) {
  for (var i = num.toString().length; i < length; i++) {
    num = '0' + num
  }
  return num
}


// 使用递归的方式添加
function addPrefix2 (num, length) {
  if (num.toString().length >= length) {
    return num
  }

  return addPrefix2('0' + num, length)
}

// 转化为小数
function addPrefix3 (num, length) {
  let decimal = num / Math.pow(10, length)

  decimal = decimal.toFixed(length)
  return decimal.substr(decimal.indexOf('.') + 1)
}

// 数组填充法
function addPrefix4 (num, length) {
  return (Array(length).join('0') + num).slice(-length)
}

// 填充截取法
function addPrefix5 (num, length) {
  var len = num.toString().length
  var diff = length - len
  if (diff > 0) {
    return Array(diff).join('0') + num
  }
}


let fix1 = addPrefix1(212, 8)
console.log(fix1) // 00000212

let fix2 = addPrefix2(21, 8)
console.log(fix2) // 00000021

let fix3 = addPrefix3(21, 8)
console.log(fix3) // 00000021

let fix4 = addPrefix4(21, 8)
console.log(fix4) // 00000021

let fix5 = addPrefix4(21, 8)
console.log(fix5) // 00000021