ITPub博客

首页 > IT职业 > IT图书 > 关于两道字符串处理的题

关于两道字符串处理的题

IT图书 作者:sealee 时间:2021-09-09 09:51:58 0 删除 编辑

1.将一串数字每三位用逗号分隔

  function formatNum(str){    var newStr = "";    var count = 0;    if(str.indexOf(".")==-1){        for(var i=str.length-1;i>=0;i--){            if(count % 3 == 0 && count != 0){
                newStr = str.charAt(i) + "," + newStr;
            }else{
                newStr = str.charAt(i) + newStr;
            }
                count++;
        }
        str = newStr + ".00"; //自动补小数点后两位
        console.log(str)
    }else{        for(var i = str.indexOf(".")-1;i>=0;i--){// 4
            // console.log('newStr:',newStr)
            if(count % 3 == 0 && count != 0){
                newStr = str.charAt(i) + "," + newStr;                // console.log('i:',i)
                // console.log('str.charAt(i):',str.charAt(i))
                // console.log('newStr:',newStr)
                // console.log('newStr:',newStr)
            }else{
                newStr = str.charAt(i) + newStr; //逐个字符相接起来
            }
            count++;
        }        console.log('newStr:',newStr)        console.log('str:',newStr +(str+'00'))        console.log((str + "00").indexOf("."))
        str = newStr + (str + "00").substr((str + "00").indexOf("."),3);        console.log(str)
    }
}

formatNum('13213.24'); //输出13,213.34formatNum('132134.2');  //输出132,134.20formatNum('132134');  //输出132,134.00formatNum('132134.236');  //输出132,134.23

2.将一串数字每四位用空格分隔

//方法1:function formatNum(str){    var array1 = str.split(''),
        array2 = [];    for(var i = 0; i  4 && i % 4 == 0){
            count += 5;            if(count != 5){                array.splice(count-1,0,' ');
            }
        }
    }

    console.log(array.join(''))
}

formatNum('132134484321882123143545412341231254642365768')



作者:饥人谷_米弥轮
链接:https://www.jianshu.com/p/c50890735195


来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/3355/viewspace-2813673/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-30

  • 博文量
    82
  • 访问量
    620