BeingSuman
BeingSuman

Reputation: 3323

Angular: Formatting numbers with commas

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.

Upvotes: 76

Views: 135785

Answers (4)

CodeWarrior
CodeWarrior

Reputation: 2851

Use DecimalPipe like this

{{attr | number}}

Working Plunker

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

Upvotes: 132

packmul3
packmul3

Reputation: 111

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

Upvotes: 6

JGFMK
JGFMK

Reputation: 8904

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

Upvotes: 20

Sebastian Giro
Sebastian Giro

Reputation: 728

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

Upvotes: 16

Related Questions