Add commas or spaces to group every three digits

Viewed 81133

I have a function to add commas to numbers:

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

Unfortunately, it doesn't like decimals very well. Given the following usage examples, what is the best way to extend my function?

commafy( "123" )                 // "123"
commafy( "1234" )                // "1234"
                                 // Don't add commas until 5 integer digits
commafy( "12345" )               // "12,345"
commafy( "1234567" )             // "1,234,567"
commafy( "12345.2" )             // "12,345.2"
commafy( "12345.6789" )          // "12,345.6789"
                                 // Again, nothing until 5
commafy( ".123456" )             // ".123 456"
                                 // Group with spaces (no leading digit)
commafy( "12345.6789012345678" ) // "12,345.678 901 234 567 8"

Presumably the easiest way is to first split on the decimal point (if there is one). Where best to go from there?

13 Answers

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

Easiest way:

1

var num = 1234567890,
result = num.toLocaleString() ;// result will equal to "1 234 567 890"

2

var num = 1234567.890,
result = num.toLocaleString() + num.toString().slice(num.toString().indexOf('.')) // will equal to 1 234 567.890

3

var num = 1234567.890123,
result = Number(num.toFixed(0)).toLocaleString() + '.' + Number(num.toString().slice(num.toString().indexOf('.')+1)).toLocaleString()
//will equal to 1 234 567.890 123

4

If you want ',' instead of ' ':

var num = 1234567.890123,
result = Number(num.toFixed(0)).toLocaleString().split(/\s/).join(',') + '.' + Number(num.toString().slice(num.toString().indexOf('.')+1)).toLocaleString()
//will equal to 1,234,567.890 123

If not working, set the parameter like: "toLocaleString('ru-RU')" parameter "en-EN", will split number by the ',' instead of ' '

All function used in my code are native JS functions. You'll find them in GOOGLE or in any JS Tutorial/Book

This is basically the same as the solution from Ghostoy, but it fixes an issue where numbers in the thousands are not handled properly. Changed '5' to '4':

export function commafy(num) {
    const str = num.toString().split('.');
    if (str[0].length >= 4) {
        str[0] = str[0].replace(/(\d)(?=(\d{3})+$)/g, '$1,');
    }
    if (str[1] && str[1].length >= 4) {
        str[1] = str[1].replace(/(\d{3})/g, '$1 ');
    }
    return str.join('.');
}
//Code in Java
private static String formatNumber(String myNum) {
    char[] str = myNum.toCharArray();
    int numCommas = str.length / 3;
    char[] formattedStr = new char[str.length + numCommas];

    for(int i = str.length - 1, j = formattedStr.length - 1, cnt = 0; i >= 0 && j >=0 ;) {
        if(cnt != 0 && cnt % 3 == 0 && j > 0) {
            formattedStr[j] = ',';
            j--;
        }

        formattedStr[j] = str[i];
        i--;
        j--;
        cnt++;
    }
    return String.valueOf(formattedStr);
}

You can do it mathematically, depending on how many digits you want to separate, you can start from one digit with 10 to 100 for 2, and so on.

function splitDigits(num) {
    num=Math.ceil(num);
    let newNum = '';
    while (num > 1000){
      let remain = num % 1000;
      num = Math.floor(num / 1000);
      newNum = remain + ',' + newNum;
    }
    return num + ',' + newNum.slice(0,newNum.length-1);
  }

At first you should select the input with querySelector like:

let field = document.querySelector("input");

and then

        field.addEventListener("keyup", () => {
            for (let i = 1 ; i <= field.value.length; i++) {
                field.value = field.value.replace(",", "");
            }
            let counter=0;

            for (let i = 1 ; i <= field.value.length; i++) {
                if ( i  % ((3 * (counter+1) ) + counter) ===0){
                    let tempVal =field.value
                    field.value = addStr(tempVal,field.value.length - i,",")
                    counter++;
                    console.log(field.value);
                }
            }
            // field.value = parseInt(field.value.replace(/\D/g, ''), 10);
            // var n = parseInt(e.target.value.replace(/\D/g,''),10);
            // e.target.value = n.toLocaleString();
        });
Related