Skip to content

Instantly share code, notes, and snippets.

@srinathweb
Created September 15, 2015 07:39
Show Gist options
  • Select an option

  • Save srinathweb/d4556276207958b15c97 to your computer and use it in GitHub Desktop.

Select an option

Save srinathweb/d4556276207958b15c97 to your computer and use it in GitHub Desktop.
format number javascript
Works on all browsers, this is all you need.
function commaSeparateNumber(val){
while (/(\d+)(\d{3})/.test(val.toString())){
val = val.toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');
}
return val;
}
Wrote this to be compact, and to the point, thanks to regex. This is straight JS, but you can use it in your jQuery like so:
$('#elementID').html(commaSeparateNumber(1234567890));
or
$('#inputID').val(commaSeparateNumber(1234567890));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment