Donate

Formatting Numbers With Comma Using Regular Expression In JavaScript

In asp.net c#, this can be achieved by String.Format(), however in javascript/jquery, this can be achieved using a simple JavaScript function:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
  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;
  }

In your script, you can call it using:
1
2
3
var number = 123456.99;  
var result = addCommas(number);  
alert(result);  

Source: JavaScript Number Format

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.

Invalid nested tag div found, expected closing tag input