Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding comma as thousands separator (javascript) - output being deleted instead

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.

like image 265
Gideon Avatar asked Nov 29 '12 08:11

Gideon


4 Answers

Try

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

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

like image 101
Dillon Benson Avatar answered Oct 18 '22 08:10

Dillon Benson


Try this regex:

function numberWithCommas(x) {
  return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
like image 24
phemt.latd Avatar answered Oct 18 '22 10:10

phemt.latd


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
like image 45
Isioma Nnodum Avatar answered Oct 18 '22 08:10

Isioma Nnodum


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
}
like image 26
technosaurus Avatar answered Oct 18 '22 09:10

technosaurus