请编写 formatNum函数,将数字转为千分位格式 ,每三位数加入逗号;var a=1234567;var b=formatNum(a);//b="1,234,567"
2 回答
千秋此意
TA贡献158条经验 获得超187个赞
function formatNum(iNum) { var count = 0, temp = iNum.toString().split(''); for (var i = temp.length - 1; i > 0; i--) { (++count % 3 === 0) && temp.splice(i, 0, ','); } return temp.join(''); } var result = formatNum(123233233233); console.log(result); // 123,233,233,233
stone310
TA贡献361条经验 获得超191个赞
function num(a) { var b = String(a).split(""); var c = ""; var num =Math.ceil(b.length/3-1); for (var i = 1; i <= num; i++) { b.splice(-i * 4 + 1, 0, ",") } for (var i = 0; i < b.length; i++) { c += b[i] } console.log(c) } num(1234567)
xuchaoi
TA贡献4条经验 获得超5个赞
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>demo</title> </head> <body> <h1>思路:输入一个数后,转成字符串再把这个字符串颠倒。接着每隔3个给一个逗号。最后把得到的字符串再颠倒过来。</h1> <script> function formatNum(num) { var strnum = num.toString(); var downNumber = strnum.split("").reverse().join(""); var number = ""; for(var i=0;i<strnum.length;i++){ if(i === (strnum.length-1)) { number += (i+1)%3 === 0 ? downNumber.substr(i-i%3,3) : downNumber.substr(i-i%3,(i+1)%3); }else{ if((i+1)%3 === 0) { number += downNumber.substr(i-2,3) + ","; } } } number = number.split("").reverse().join(""); return number; } var num = 12394723942; //随便输入一个数 var result = formatNum(num); console.log("原值:" + num); console.log("格式后的值:" + result); </script> </body> </html>
添加回答
举报
0/150
提交
取消