您好,欢迎访问一九零五行业门户网

js怎么补齐数字

js补齐数字的方法:1、通过迭代方式实现;2、通过“num/math.pow(10, length);”方法实现;3、通过“(array(length).join('0') + num).slice(-length);”实现。
例如我们希望输出的数字长度是固定的,假设为10,如果数字为123,则输出0000000123,不够位数就在之前补足0。当然你也可以根据本章的代码自行更改想补得数字。
这里提供了三种不同的方式实现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怎么补齐数字的详细内容。
其它类似信息

推荐信息