In angular 2, how to display a number as two decimal rounded currency?

g.sui picture g.sui · Jan 22, 2016 · Viewed 66.7k times · Source

Examples:

  • 1.99 --> $1.99
  • 1.9 --> $1.90
  • 1 --> $1.00
  • 1.005 --> $1.01
  • 1.004 --> $1.00

I am using {{num | currency:'USD':true}} but it does not show trailing 0s.

Answer

Mubashir picture Mubashir · Jan 22, 2016

Use this code. Here is a working example http://plnkr.co/edit/xnN1HnJtTel6WA24GttR?p=preview {{num | currency:'USD':true:'1.2-2'}}

Explanation :
number_expression | number[:digitInfo]

Finally we get a decimal number as text. Find the description.

number_expression: An angular expression that will give output a number.

number : A pipe keyword that is used with pipe operator.

digitInfo : It defines number format.

Now we will understand how to use digitInfo. The syntax for digitInfo is as follows.

{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}

Find the description.

minIntegerDigits : Minimum number of integer digits. Default is 1. (in our case 1)

minFractionDigits : Minimum number of fraction digits. Default is 0. (in our case 2)

maxFractionDigits : Maximum number of fraction digits. Default is 3. (in our case 2)