I'm trying to do a currency format for my input, which I want to automatically format with thousands separator(",") and decimals; I tried with several plugins but they do not work for me.
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;
}
This adds commas to me, but only for the first unit of thousands :(
This example here works, but on a blur event, how do I run it on a keyup event.
$("#number").keyup(function() {
this.value = parseFloat(this.value.replace(/,/g, ""))
.toFixed(2)
.toString()
.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
});