Angular: formatting numbers with commas

The title sums up my needs a lot.

123456789 => 123,456,789 12345 => 12,345 

What is the best way to get this conversion? Do not offer a currency pipe in Angular -2, because I do not need the $ symbol or currency, which should be added to my result.

+5
source share
3 answers

Use a DecimalPipe like this

{{attr | number}}

Working plunker
Documentation is available at https://angular.io/api/common/DecimalPipe

+7
source

Without using pipes, an easy way to answer your question with javascript is:

 var str = "The quick brown fox jumps over the lazy dogs.".replace(/(.{2})/g,"$1,"); 

And this will output Th,e ,qu,ic,k ,br,ow,n ,fo,x ,ju,mp,s ,ov,er, t,he, l,az,y ,do,gs,.

But I think that you have formulated your question poorly, so if you want to parse numbers, you should use this function:

 function numberWithCommas(x) { var parts = x.toString().split("."); parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ","); return parts.join("."); } 

So

 var num = numberWithCommas(1234567); console.log(num); 

This will exit 1,234,567

+2
source
 <!DOCTYPE html> <html> <head> <script type="text/javascript"> function printNo() { document.getElementById('text').innerHTML = Number(1234355).toLocaleString('en-GB'); } </script> </head> <body onload="printNo()"> <h1 id="text"></h1> </body> </html> 

https://plnkr.co/edit/OU0koo2r1YuKC1rC3tpN?p=preview https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

+1
source

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


All Articles