JavaScript实现数字前补“0”的五种方法示例
2022/8/23 1:55:18
本文主要是介绍JavaScript实现数字前补“0”的五种方法示例,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
来自:https://www.jb51.net/article/153945.htm 侵删
<!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) { 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”的五种方法示例的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-23Springboot应用的多环境打包入门
- 2024-11-23Springboot应用的生产发布入门教程
- 2024-11-23Python编程入门指南
- 2024-11-23Java创业入门:从零开始的编程之旅
- 2024-11-23Java创业入门:新手必读的Java编程与创业指南
- 2024-11-23Java对接阿里云智能语音服务入门详解
- 2024-11-23Java对接阿里云智能语音服务入门教程
- 2024-11-23JAVA对接阿里云智能语音服务入门教程
- 2024-11-23Java副业入门:初学者的简单教程
- 2024-11-23JAVA副业入门:初学者的实战指南