关于两道字符串处理的题

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.34
formatNum('132134.2');  //输出132,134.20
formatNum('132134');  //输出132,134.00
formatNum('132134.236');  //输出132,134.23

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

//方法1:
function formatNum(str){
    var array1 = str.split(''),
        array2 = [];

    for(var i = 0; i < array1.length; i++){
        if(i != 0 && i % 4 === 0){
            array2.push(' ');
            array2.push(array1[i]);
        }else{
            array2.push(array1[i]);
        }
    }

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

formatNum('132134484321882')

//方法2:
function formatNum(str){
    var array = str.split('');
    var count = 0;

    for(var i = 0; i <= array.length; i++){
        if(i != 0 && i == 4){
            array.splice(i,0,' ');
        }
        if(i > 4 && i % 4 == 0){
            count += 5;
            if(count != 5){
                array.splice(count-1,0,' ');
            }
        }
    }

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

formatNum('132134484321882123143545412341231254642365768')
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容