Reputation: 6264
I have following function in jQuery to format the number into comma-formatted:
function CommaFormattedN(amount) {
var delimiter = ",";
var i = parseInt(amount);
if(isNaN(i)) { return ''; }
i = Math.abs(i);
var minus = '';
if (i < 0) { minus = '-'; }
var n = new String(i);
var a = [];
while(n.length > 3)
{
var nn = n.substr(n.length-3);
a.unshift(nn);
n = n.substr(0,n.length-3);
}
if (n.length > 0) { a.unshift(n); }
n = a.join(delimiter);
amount = minus + n;
return amount;
}
I am calling this function like this on
$('.text_field1').bind("focus blur change keyup", function(){
var $el = $(this);
$el.val(CommaFormattedN($el.val()));
});
It's working fine, but the problem is, when number of digits increase from 5, it makes nothing. All digits are deleted and it starts again.
Upvotes: 0
Views: 2541
Reputation: 272096
You can use Number.toLocaleString() function to format a number into a locale specific format. Note that the output of the function varies with regional settings:
var n = parseInt("-123456789", 10);
console.log(n.toLocaleString())
// returns -123,456,789 on my computer (english-us locale)
// returns -123 456 789 for french locale
// returns -123.456.789 for german locale
// returns -123'456'789 for romansh (???) locale
Upvotes: 6
Reputation: 43235
Here is your working code with minor edit ( sign related ) : http://jsfiddle.net/qcVDc/1/
Upvotes: 2