Search code examples
javascriptstring-formatting

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


Need to format the number into blocks of a length of three, separated with commas. If required, the second last block can be of length two, like 987,234,65,43 The last block cannot be of length one(046,435,699,8). The last block should be a length of two or three, it should not be one.

Examples: "223,334,874,498"
"987,234,65,43"
"487,534,354,23"

Below is the code, but in this code, I am not able to make that last block to the length of 2 or 2 digits. For "0464356998" ---Current Output is:046,435,699,8 --- But Expected Output is: 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

    

Solution

  • I'm not sure that this is best way but n is string so you can slice and you can count length of string

    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 For any string from 6 to ...

    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