59

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.

CodeWarrior
  • 2,571
  • 3
  • 17
  • 18
BeingSuman
  • 2,563
  • 7
  • 27
  • 46
  • 1
    Possible duplicate of [How to print a number with commas as thousands separators in JavaScript](https://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript) – gforce301 Jul 05 '17 at 14:41
  • 1
    @gforce301 It's a different enviroment, the op wanted a solution for angular2 too, as CodeWarrior answered with a pipe solution. – Sebastian Giro Jul 05 '17 at 15:16

4 Answers4

107

Use DecimalPipe like this

{{attr | number}}

Working Plunker

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

CodeWarrior
  • 2,571
  • 3
  • 17
  • 18
15

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

Prashant Pimpale
  • 9,685
  • 7
  • 35
  • 75
JGFMK
  • 7,713
  • 4
  • 52
  • 86
13

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

Sebastian Giro
  • 688
  • 1
  • 7
  • 17
3

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

packmul3
  • 61
  • 4