如何将数字格式化为以逗号分隔的长度为 3 的块,最后 2 个块或最后一个块的长度可以为 2,但不能为 1

How to format numbers to block of length three separated by comma, last 2 blocks or last block can be length of two but it cannot be length of one

需要将数字格式化为三个长度的块,用逗号分隔。 如果需要,倒数第二个块的长度可以为 2,例如 987,234,65,43 最后一个块的长度不能为 one(046,435,699,8)。 最后一个块的长度应该是二三,应该不是一。

例子: “223,334,874,498”
“987,234,65,43”
“487,534,354,23”

下面是代码,但在这段代码中,我无法将最后一个块的长度设为 2 或 2 位数字。 对于“0464356998”---当前输出is:046,435,699,8 --- 但预期输出是:046,435,69,98

function format(N) {     

    return N.replace(/[^0-9]/g, '') 
    // Replace everything which are not a number   

    // Spilt on every 3rd number
    .match(/\d{1,3}/g)  

    // Join with commas
    .join(',')     
    }
    console.log(format("0464356998"));
    //Current output:  046,435,699,8
    //expected Output: 046,435,69,98

    

我不确定这是最好的方法,但 n 字符串 所以你可以 slice 并且你可以数 length字符串

function format(n) {  
  if((n.length - 6) % 2 === 0){ // is (n.length - 6) is divisible without remainder
    return `${n.slice(0,3)}, ${n.slice(3,6)}, ${n.slice(6,8)}, ${n.slice(8,10)}`
  }else{
    return `${n.slice(0,3)}, ${n.slice(3,6)}, ${n.slice(6,9)}, ${n.slice(9,12)}`
  }
}


console.log(format("0464356998"));
console.log(format("04643569981"));

UPD 对于从 6 到 ...

的任何字符串

function formatter(n) {
    let a = [];
    for (let i = 0; i < n.length / 3; i++) {
      a.push(n.slice(i * 3, (i + 1) * 3));
    }

    if (a[a.length - 1].length === 1){
      let b = a[a.length - 2].substring(2,3)
      let c = a[a.length - 1];
      a[a.length - 2] = a[a.length - 2].slice(0, 2);
      a[a.length - 1] = b.concat(c);
    }
    return a.join();
  }
  console.log(formatter("0464356998")); // 10
  console.log(formatter("04643569982")); // 11
  console.log(formatter("046435699823")); // 12
  console.log(formatter("0464356998231")); // 13
  console.log(formatter("04643569982316")); // 14
  console.log(formatter("046435699823156")); // 15
  console.log(formatter("0464356998231675")); // 16
  console.log(formatter("04643569982315634")); // 17
  console.log(formatter("046435699823167556")); // 18
  console.log(formatter("046435699810464356998")); // 21
  console.log(formatter("0464356998104643569981")); // 22