将字符串或者数字转化成英文格式输出

时间:2023-01-04 10:17:01
var f = function(a){
    var b = String(a);
    var len = b.length;
    var j = len % 3;
    var arr = [];

    if (len <= 3) {return b};
    if (j==0) {
        return m(arr,b,len,0);
    }else{
        arr[0] = b.substr(0,j);
        b = b.substr(j);
        return m(arr,b,len,1);
    }

        
}

var m = function(arr,b,len,k){
    for (var i = k; i < len/3; i++) {
        arr[i] = b.substr(0,3);
        b = b.substr(3);
    }
    return arr.join(",");

}

暂时这么写,以后有更好的方式再来更新。

                                                                  6.10

 

 

 

补充: 第一种方法效率太差

//方法二
console.time("2")
function splitStr2(str){
        var len = str.length;
        var n = parseInt(len/3);
        if (len%3 === 0){
            --n;
        }
        for(var i = n; i > 0; i--){
            str = str.substr(0, len-3*(n+1-i))+","+str.substr(len-3*(n+1-i), 3*(n+1-i)+n-i);
        }
        return str;
    }
    splitStr2("1234567890");
    console.timeEnd("2")
//方法三
//
console.time("3")
function splitStr3(str){
        var len = str.length;
        var n = parseInt(len/3);
        if (len%3 === 0){
            --n;
        }
        for (var i = 0; i < n; i++)
            str += "1";
        var tmp = str.split('');
        for (var i = len - 1; i > 2; i -= 3){
            tmp[i+n] = tmp[i];
            tmp[i+n-1] = tmp[i-1];
            tmp[i+n-2] = tmp[i-2];
            tmp[i+n-3] = ",";
            n--;
        }
        tmp.join('');
    }
    splitStr3("1234567890");
console.timeEnd("3");


//方法四
console.time("4");
function splitstr4 (str) {
    // body...
    var tmp = "";
    var r = "";
    for (var len = str.length,i=len-1; i >= 0; i--) {
        tmp = str[i] + tmp;
        if (tmp.length == 3) {
            r = " ," + tmp + r;
            tmp = "";

        };
    };
    r = tmp + r;
    if (len % 3 === 0) {
        r = r.substr(2);
    };
    return r;
}

splitstr4("1234567890");
console.timeEnd("4")

//方法五
console.time("5")

function changeStr(str) {
  var len = str.length;
  var n = len % 3;
  var pat = /\d\d\d/g;
  var m;
  var arr = [
  ];

  if (n != 0) {
    arr[0] = str.substr(0,n);
    str= str.substr(n);
    for (var i = 0; i < len / 3; i++) {
      m = pat.exec(str);
      arr[i + 1] = m[0];
    }
  } else {
    for (var i = 0; i < len / 3; i++) {
      m = pat.exec(str);
      arr[i] = m[0];
    }
  }
  return arr.join(",");
}
changeStr('123456789')
console.timeEnd("5")