vishal_g vishal_g - 4 months ago 12
jQuery Question

How to add commas format in number after page load using jquery

I have one page which is having bank funds summary details and i am getting all these value from API. These values are not formatted for example like 50000.3645656.

So here is my page structure given below

<span class="format">50000.3645656</span>
<span class="format">50000.3645656</span>
<span class="format">50000.3645656</span>
<span class="format">50000.3645656</span>
<span class="format">50000.3645656</span>


So what i want exactly is , I want to format all these value with comma formated with two decimal point like 50,000.36.

How can i do this after page load using jquery and css class format in jquery method.

Answer

As far as I know, you can't do this using pure CSS.

However, you could use a JavaScript function to add commas for you.

I have used this one in the past:

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

Reference

And then do your jquery:

$(function(){
   $(".format").each(function(c, obj){
      $(obj).text(addCommas(parseFloat($(obj).text()).toFixed(2)));
   });
});

JSfiddle Demonstration:

Comments