Angular: Formatting numbers with commas

Viewed 98153

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.

4 Answers

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

Related