Adding commas to numbers with JavaScript

I recently went to add commas to a number on entry. Found a nice script here. Only thing I changed was to make it set the value in the function. I also liked his solution for adding separators other than commas.

The code:

function addCommas(obj) {
    nStr = obj.value;
    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');
    }
    obj.value = x1 + x2;
}

Comments

Popular posts from this blog

Migrating Legacy Apps to the New SimpleMembership Provider

Windows 8 Keyboard Shortcuts

Get Asp.Net Profile properties from Sql