satheesh babu

satheesh babu

  • NA
  • 128
  • 312.6k

How to add the comma in the number with java script?

Aug 29 2011 2:20 AM
Hi all,

I want to add/insert a comma in between the number(money) like below.

123456.63 will be like 1,23,456.63 (XX,XX,XXX.XX) with java script for a text box key up event.

i used below javascript function but its not working fine.

function addCommas() {
var nStr = document.getElementById('txtamount').value;
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d{2})(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
//return x1 + x2;
document.getElementById('txtamount').value = x1 + x2;
}

for the above function below is the result. if the number have 4 digits in the end it is not inserting a number.

12,34,56,45,6954

And if i enter number like 12345 then it need to show 12,345 as well as if press back space to delete number 5 then it need re align to 1,234.

Please tell me any other regular expression.

Answers (1)