js怎么补齐数字


当前第2页 返回上一页

方法一:迭代方式实现

1

2

3

4

5

6

function PrefixInteger(num, length) {

  for(var len = (num + "").length; len < length; len = num.length) {

   num = "0" + num;

   }

  return num;

}

方法二:转为小数

1

2

3

4

5

6

function PrefixInteger(num, length) {

 var decimal = num / Math.pow(10, length);

  //toFixed指定保留几位小数

  decimal = decimal.toFixed(length) + "";

  return decimal.substr(decimal.indexOf(".")+1);

}

方法三:更高效

1

2

3

function PrefixInteger(num, length) {

 return (Array(length).join('0') + num).slice(-length); 

}

测试:

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<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) {

  var decimal = num / Math.pow(10, length);

  //toFixed指定保留几位小数

  decimal = decimal.toFixed(length) + "";

  return decimal.substr(decimal.indexOf(".")+1);

 }

 //填充截取法

 function padding3(num, length) {

  //这里用slice和substr均可

  return (Array(length).join("0") + num).slice(-length);

 }

 

 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));

 }

 test(123, 10);

</script>

</body>

</html>

结果:

1

2

3

0000000123 

0000000123 

0000000123

以上就是js怎么补齐数字的详细内容,更多文章请关注木庄网络博客

返回前面的内容

相关阅读 >>

js中“==”和“===”有什么区别

详细介绍js中的变量提升机制

使用javascript的模块加载器

web学习之怎么使用纹理贴图

js实现双色球效果

了解js中!/+/-/~ function() {/*...*/}()是什么意思

js如何实现简单的秒表效果

vue和node是什么关系

js实现点击目录名变换颜色的效果实例

浅谈json.stringify()和json.parse()的应用

更多相关阅读请进入《js》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...