Method one: Number. The prototype. ToLocaleString ()

Returns the locale-specific representation string for this number.

For a detailed description of the method, see MDN developer.mozilla.org/zh-CN/docs/…

let num = 123456789;
num.toLocaleString()/ / "123456789"
Copy the code

This method is very convenient, but compatibility is not very good

Method 2: Match by re

    let num = '12345678'
    let reg = / (? =\B(\d{3})+$)/g
    console.log(num.replace(reg,",")) //12,345,678
Copy the code

Method 3: Custom method separation

Implementation idea:

  • Converts the number passed in by the user to a string.
  • The string is split into an array using the split method, and then reversed using the reverse method.
  • The number of split digits passed in by the user determines how many groups of values need to be divided.
  • Defines a new array to hold delimited arrays.
  • Loop through the number of groups to determine the position of the delimiter.
  • In this case, we need to delete the delimiter, then reverse the array with the delimiter added, and finally convert it to a string through join.
    function fn(num, sep, size) {
      num += "";
      let numArr = num.split("").reverse();
      let group = parseInt(numArr.length / size);
      let resArr = []
      // Sets a variable to control the start and end of array splitting
      let i = 0;
      while (group) {
        // Determine the position of the delimiter
        resArr = [...resArr, ...numArr.slice(size * i, size * (i + 1)), sep]
        group--;
        i++;
      }
      // Indicates the number of array elements involved in the split
      const restIndex = resArr.length - parseInt(numArr.length / size);

      // Add the ungrouped elements to the delimited array
      resArr = [...resArr, ...numArr.slice(restIndex)]
      // Invert the delimited array and convert it to a string.
      let strNum = resArr.reverse().join(' ')
      if (strNum[0] === sep) {
        strNum = strNum.slice(1)}return strNum;
    }
    console.log(fn(12345678.', '.3)) //12,345,678
Copy the code