关于两道字符串处理的题

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')

你可能感兴趣的:(关于两道字符串处理的题)