Add commas or spaces to group every three digits

前端 未结 9 1689
日久生厌
日久生厌 2020-11-27 15:50

I have a function to add commas to numbers:

function commafy( num ) {
  num.toString().replace( /\\B(?=(?:\\d{3})+)$/g, \",\" );
}

Unfortun

9条回答
  •  醉梦人生
    2020-11-27 16:32

    Here are two concise ways I think maybe useful:

    1. Number.prototype.toLocaleString

    This method can convert a number to a string with a language-sensitive representation. It allows two parameters, which is locales & options. Those parameters may be a bit confusing, for more detail see that doc from MDN above.

    In a word, you could simply use is as below:

    console.log(
       Number(1234567890.12).toLocaleString()
    )
    // log -> "1,234,567,890.12"
    

    If you see different with me that because we ignore both two parameters and it will return a string base on your operation system.

    1. Use regex to match a string then replace to a new string.

      Why we consider this? The toLocaleString() is a bit confusing and not all browser supported, also toLocaleString() will round the decimal, so we can do it in another way.

    // The steps we follow are:
    // 1. Converts a number(integer) to a string.
    // 2. Reverses the string.
    // 3. Replace the reversed string to a new string with the Regex
    // 4. Reverses the new string to get what we want.
    
    // This method is use to reverse a string.
    function reverseString(str) { 
        return str.split("").reverse().join("");  
    }
    
    /**
     * @param {string | number} 
     */
    function groupDigital(num) {
      const emptyStr = '';
      const group_regex = /\d{3}/g;
    
      // delete extra comma by regex replace.
      const trimComma = str => str.replace(/^[,]+|[,]+$/g, emptyStr)
    
    
      const str = num + emptyStr;
      const [integer, decimal] = str.split('.')
    
      const conversed = reverseString(integer);
    
      const grouped = trimComma(reverseString(
        conversed.replace(/\d{3}/g, match => `${match},`)
      ));
    
      return !decimal ? grouped : `${grouped}.${decimal}`;
    }
    
    
    console.log(groupDigital(1234567890.1234)) // 1,234,567,890.1234
    console.log(groupDigital(123456))  // 123,456
    console.log(groupDigital("12.000000001"))  // 12.000000001
    
    

提交回复
热议问题