时间:2021-07-01 10:21:17 帮助过:46人阅读
这里提供了三种不同的方式实现JS代码给数字补0 的操作:
方法一:迭代方式实现
function PrefixInteger(num, length) { for(var len = (num + "").length; len < length; len = num.length) { num = "0" + num; } return num; }
方法二:转为小数
function PrefixInteger(num, length) { var decimal = num / Math.pow(10, length); //toFixed指定保留几位小数 decimal = decimal.toFixed(length) + ""; return decimal.substr(decimal.indexOf(".")+1); }
方法三:更高效
function PrefixInteger(num, length) { return (Array(length).join('0') + num).slice(-length); }
测试:
<!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>
结果:
0000000123 0000000123 0000000123
以上就是js怎么补齐数字的详细内容,更多请关注Gxl网其它相关文章!