How to add comma format to number after page load using jquery

I have one page that shows the summary data of bank funds, and I get all these values ​​from the API. These values ​​are not formatted, for example, as 50000.3645656.

So here is my page structure 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 for sure is this, I want to format all these values ​​with a comma formed with two decimal points, for example, 50,000.36.

How to do this after loading the page using jquery format and css in jquery format.

+4
source share
3 answers

As far as I know, you cannot do this using pure CSS.

JavaScript .

:

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;
}

jquery:

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

JSfiddle :

+6

Using:

    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

0
source

Source: https://habr.com/ru/post/1524678/


All Articles