I need to format a number like 1234567
as 1,234,567
but don't know how to do this. I tried using currency pipe of TypeScript but that gives USD or $ in front of the number. I want to remove that and format the number in this way 1,234,567
. How can I do this?
3 Answers
Just use the number (decimal) pipe instead.
To give an example:
{{ '1234567' | number:'1.0':'en-US' }}
will produce output 1,234,567
.
If you do not change the default locale (by calling registerLocaleData()
or providing LOCALE_ID), then simple {{'1234567' | number}}
will work as well.
-
13or even simpler,
(123456789).toLocaleString()
, because JavaScript has this built in =) Commented Nov 17, 2016 at 17:57 -
This is probably the best solution, but usage examples would be good to make this more useful than a link-only answer. Commented Nov 17, 2016 at 17:59
-
1@Aurora0001, example added. I haven't expected this question to get such engagement :) Commented Nov 17, 2016 at 18:06
-
2@Mike, that's a very limited and unstable solution. For me
(1234567).toLocaleString()
produces1 234 567
. Even if the result was correct, I wouldn't use it in a serious project when better way is available. Commented Nov 17, 2016 at 18:09 -
4@DanielKucal remember to add the local itself.
(1234567).toLocaleString("en")
if you need commas. With explicit locale, this is the most correct solution Commented Nov 17, 2016 at 22:03
The last answer will produce 1,234,567.00
Note the 2 decimals.
Use the following Pipe:
{{ element.total | number: '2.'}}
In order to produce 1,234,567
-
7This produces single digit numbers as 01, 02, 03, etc. To just add commas, you can just use
{{ element.total | number }}
.– Jun KangCommented Sep 13, 2018 at 18:07 -
Provide a link in the comment instead of copying pasting the same answer. stackoverflow.com/a/50364297/894532 Commented Jan 21, 2019 at 0:40
-
What can we do in the Component file to modify data if i don't have the option to add pipe in template? Commented Jun 28, 2019 at 13:39
-
use these (taken from tutorialspoint.com/typescript/typescript_number_tofixed.htm): num3.toFixed() is 177 num3.toFixed(2) is 177.23 num3.toFixed(6) is 177.234000– ItamarCommented Jul 7, 2019 at 12:18
Per the official Angular documentation for the DecimalPipe, which is defined with the structure {{ value_expression | number [ : digitsInfo [ : locale ] ] }}
, I was able achieve the desired number formatting by using:
{{ myValue | number:'':'en' }}
The empty string (''
) causes the pipe to uses the default digitsInfo
values for minIntegerDigits
(1), minFractionDigits
(0), and maxFractionDigits
(3).
The locale being set to en
causes the value to be displayed with commas marking the thousands, millions, etc. positions.
-
1piggybacking on this
{{ myVAlue | number }}
also appears to work since the default locale is en-us. Commented May 30, 2019 at 23:57
toLocaleString()
)