Angular: Formatting numbers with commas

JavascriptAngularTypescript

Javascript Problem Overview


Title very much sums up my needs.

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

What's the best way to get this conversion ? Don't suggest currency pipe in Angular-2 as I don't need $ or currency symbol to be prepend to my output.

Javascript Solutions


Solution 1 - Javascript

Use DecimalPipe like this

{{attr | number}}

Working Plunker

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

Solution 2 - Javascript

function printNo() {
  document.getElementById('text').innerHTML =
  Number(1234355).toLocaleString('en-GB');
}

 <!DOCTYPE html>
 <html>
    <head></head>
    
     <body onload="printNo()">
      <h1 id="text"></h1>
        
     </body>
</html>

Reference link

Solution 3 - Javascript

Without using pipes, a simple way to answer your question with javascript:

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 you formulated your question bad, 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 output 1,234,567

Solution 4 - Javascript

CodeWarrior's answer on pipes works great for front-end display. Recommended if your number is easy to isolate and pipe in your HTML. Sometimes though, it is much more convenient to get the formatted number in Typescript/Javascript before assembling something for display.

For Typescript in Angular, formatNumber() from @angular/common will comma separate numbers. With num as a string of "12345":

formatNumber(Number(num), 'en-US', '1.0-0')

will produce "12,345" as another string. Obviously different locales will format the number differently ('en-US' uses ',' and '.'), and the third option of digitsInfo can define whether your want decimals or not ('1.0-0' suggests one digit before '.' and zero after).

You will need to import formatNumber with

import {formatNumber} from '@angular/common';

Documentation at https://angular.io/api/common/formatNumber

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBeingSumanView Question on Stackoverflow
Solution 1 - JavascriptCodeWarriorView Answer on Stackoverflow
Solution 2 - JavascriptJGFMKView Answer on Stackoverflow
Solution 3 - JavascriptSebastian GiroView Answer on Stackoverflow
Solution 4 - Javascriptpackmul3View Answer on Stackoverflow