9

I am attempting to dynamically adjust a numerical value entered to include thousand separators

Here is my code:

function addCommas(nStr) {
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}


<input type="number"  onkeyup="this.value=addCommas(this.value);" />

However when I enter numbers after the 4 one, the field is cleared.

Any ideas where I am going wrong? If there is a jQuery solution I'm already using that on my site.

phant0m
  • 16,595
  • 5
  • 50
  • 82
Gideon
  • 1,878
  • 4
  • 40
  • 71

5 Answers5

13

Try this regex:

function numberWithCommas(x) {
  return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
phemt.latd
  • 1,775
  • 21
  • 33
8

To add the thousands separator you could string split, reverse, and replace calls like this:

function addThousandsSeparator(input) {
    var output = input
    if (parseFloat(input)) {
        input = new String(input); // so you can perform string operations
        var parts = input.split("."); // remove the decimal part
        parts[0] = parts[0].split("").reverse().join("").replace(/(\d{3})(?!$)/g, "$1,").split("").reverse().join("");
        output = parts.join(".");
    }

    return output;
}

addThousandsSeparator("1234567890"); // returns 1,234,567,890
addThousandsSeparator("12345678.90"); // returns 12,345,678.90
Isioma Nnodum
  • 1,318
  • 13
  • 13
6

Try

<input type="text" onkeyup="this.value=addCommas(this.value);" />

instead. Since the function is working with text not numbers.

Dillon Benson
  • 4,280
  • 4
  • 23
  • 25
2

as Dillon mentioned, it needs to be a string (or you could use typeof(n) and stringify if not)

function addCommas(n){
    var s=n.split('.')[1];
    (s) ? s="."+s : s="";
    n=n.split('.')[0]
    while(n.length>3){
        s=","+n.substr(n.length-3,3)+s;
        n=n.substr(0,n.length-3)
    }
    return n+s
}
technosaurus
  • 7,676
  • 1
  • 30
  • 52
2

In each case before formatting try to remove existing commas first, like there: Removing commas in 'live' input fields in jquery

Example:

function addThousandsSeparator(x) {
    //remove commas
    retVal = x ? parseFloat(x.replace(/,/g, '')) : 0;

    //apply formatting
    return retVal.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
Community
  • 1
  • 1
V.K.
  • 101
  • 1
  • 4
  • This seems to be the best answer, the only issue is that when the field is empty "0" is returned and I cannot determine why. – tekstrand May 07 '15 at 20:33