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, ",");
});
If you had, for example:
So with JQuery 1 :
* See in JSFiddle .
Grades
Today, most modern browsers support Intl.NumberFormat which helps us format a number without resorting to regular expressions or jQuery-specific functions.
To display comma as thousands separator, use it as follows
I use for that case jquery.maskedinput.min.js a plugin that formats the input of the input
A simple example is
In addition to numbers, it allows you to format more input data.
Use jQuery jquery.maskedinput.min.js in the mask function, you give it the format you want your input to have
here I leave you a function
javascript
that allows you to format a number according to a given mask, in addition the function allows you to process formulate.