Monday, December 13, 2010

Formatting numbers with comma 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

0 comments:

Post a Comment