4

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.

vishal_g
  • 3,871
  • 4
  • 21
  • 34

3 Answers3

6

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:

mohlman3
  • 311
  • 3
  • 7
0

As an alternative why not using a tiny library that does the job well:

http://josscrowcroft.github.io/accounting.js/

roland
  • 7,695
  • 6
  • 46
  • 61
0

Use:

    var input = '55021.1231';
    var parts = input.split('.');
    var part1 = parts[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
    var part2 = parseFloat('0.'+parts[1]).toFixed(2);
    part2=part2.split('.');
    alert(part1 + '.' + part2[1]);

Demo

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125