I am trying to make a coin format for my input, which I want to be formatted automatically with thousand separator (",") and decimals; try 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 me commas, but only for the first unit of thousands: (
This example here works, but in a blur event, as I do to execute it in a keyup event.
$("#number").keyup(function() {
this.value = parseFloat(this.value.replace(/,/g, ""))
.toFixed(2)
.toString()
.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
});