Formatting Currency Using Pipe in Angular
The CurrencyPipe channel can be used to format the currency output. The first parameter of the channel is the currency code according to the ISO 4217 specification (USD by default). The second parameter is used to set the currency display. It can take the following values: 'code' (the currency code), 'symbol' (its symbol), 'symbol-narrow' (for countries with several currency symbols), 'string' (to output any string). In the third optional parameter, we can set the number format similar to the DecimalPipe channel. In the fourth optional parameter you can specify the code of the locale used:
<div>{{ value | number : currency code : currency display : number format : locale code }}</div>
Examples
Let's try the channel's work on examples. To do this, in the component class we will set the following property salary, containing the salary in some currency:
export class AppComponent {
salary: number = 867.564;
}
Example
Let's convert our number into currency:
<div>{{ salary | currency }}</div>
Result of code execution:
<div>$867.56</div>
Example
Now let's specify the currency display in Russian rubles:
<div>{{ salary | currency:'RUB':'code' }}</div>
Result of code execution:
<div>RUB867.56</div>
Example
Let's display the Russian ruble symbol next to the number:
<div>{{ salary | currency:'RUB':'symbol-narrow' }}</div>
Result of code execution:
<div>₽867.56</div>
Example
Now let's take a number with four digits in the fractional part:
<div>{{ salary | currency:'RUB':'symbol':'2.4-5' }}</div>
Result of code execution:
<div>RUB867.5640</div>
Example
Let's add the following line to the currency display:
<div>{{ salary | currency:'RUB':'this is a new currency - ' }}</div>
Result of code execution:
<div>this is a new currency - 867.56</div>
Practical tasks
Given a number:
salary: number = 134.89;
Format it as follows:
'$134.89'
Given a number:
salary: number = 134.89;
Format it as follows:
'€134.89'
Given a number:
salary: number = 134.89;
Format it as follows:
'$134.890'
Given a number:
salary: number = 134.89;
Format it as follows:
'$0,134.8900'
Given a number:
salary: number = 134.89;
Format it as follows:
'this currency is changed 134.89'