JavaScript实现数字前补“0”的五种方法示例
Posted raineliflor
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaScript实现数字前补“0”的五种方法示例相关的知识,希望对你有一定的参考价值。
众所周知javascript中的数字是没有前置0的,因此需要我们自己进行操作来添加前置0,而且还得转换成字符串。
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
58
59
60
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" <head> <meta http-equiv= "Content-Type" content= "text/html; charset=utf-8" /> <title>JavaScript 数字前补“0”</title> <body> <script> //迭代方式实现 function padding1(num, length) { for ( var len = (num + "" ).length; len < length; len = num.length) { num = "0" + num; } return num; } //递归方式实现 function padding2(num, length) { if ((num + "" ).length >= length) { return num; } return padding2( "0" + num, length) } //转为小数 function padding3(num, length) { var decimal = num / Math.pow(10, length); //toFixed指定保留几位小数 decimal = decimal.toFixed(length) + "" ; return decimal.substr(decimal.indexOf( "." )+1); } //填充截取法 function padding4(num, length) { //这里用slice和substr均可 return (Array(length).join( "0" ) + num).slice(-length); } //填充截取法 function padding5(num, length) { var len = (num + "" ).length; var diff = length - len; if (diff > 0) { return Array(diff).join( "0" ) + num; } return num; } function test(num, length) { document.write(padding1(num, length)); document.write( "<br>" ); document.write(padding2(num, length)); document.write( "<br>" ); document.write(padding3(num, length)); document.write( "<br>" ); document.write(padding4(num, length)); document.write( "<br>" ); document.write(padding5(num, length)); document.write( "<br>" ); } test(123, 10); test(1234567890123, 10); </script> </body> </html> |
输出
0000000123
0000000123
0000000123
0000000123
000000123
1234567890123
1234567890123
4567890123
4567890123
1234567890123
以上是关于JavaScript实现数字前补“0”的五种方法示例的主要内容,如果未能解决你的问题,请参考以下文章