Using the CurrencyPipe in Angular

Angular provides a wide range of built-in pipes that help transform data in templates. One of the most commonly used pipes for displaying monetary values is the CurrencyPipe. The CurrencyPipe formats numeric values into currency strings according to locale and formatting options.

In this comprehensive guide, we will cover everything about using the CurrencyPipe, including its syntax, parameters, localization features, dynamic configuration, and practical use cases in real-world applications.

Introduction to Pipes in Angular

Pipes in Angular are simple functions that take an input value, transform it, and return a formatted output. They are especially useful in templates for transforming data without changing the actual model.

Angular includes several built-in pipes such as:

  • DatePipe for formatting dates
  • UpperCasePipe and LowerCasePipe for text transformation
  • DecimalPipe and PercentPipe for numeric formatting
  • CurrencyPipe for representing values as currency

The CurrencyPipe is particularly useful when building applications that deal with prices, sales, invoices, or financial data.

What Is the CurrencyPipe

The CurrencyPipe is a part of Angular’s CommonModule and is used to display numbers as currency values. It automatically applies locale-specific formatting and symbols.

For example, if you have a value 1000, you can display it as $1,000.00 in the United States or €1.000,00 in Europe, depending on the locale settings.

The syntax of the CurrencyPipe is simple but very powerful once you understand its parameters.


Basic Syntax of CurrencyPipe

The basic syntax for using the CurrencyPipe in a template is:

{{ value | currency }}

This automatically formats the numeric value according to the default currency and locale settings of the application.

For instance, if your locale is set to en-US and the value is 1000, it will display as:

$1,000.00

This default behavior assumes US dollars and the default number of fraction digits (two decimal places).


Full Syntax with Parameters

The CurrencyPipe supports up to four parameters for advanced formatting control.

{{ value | currency:currencyCode:display:digitsInfo:locale }}

Let’s understand what each of these parameters means.


1. currencyCode

The currencyCode specifies which currency to use, such as USD, EUR, GBP, or PKR.

Example:

<p>{{ price | currency:'EUR' }}</p>

Output:

€99.99

This will display the price in euros.


2. display

The display parameter controls whether to show the symbol (like $) or the code (USD).

Example 1 (symbol):

<p>{{ price | currency:'USD':'symbol' }}</p>

Output:

$99.99

Example 2 (code):

<p>{{ price | currency:'USD':'code' }}</p>

Output:

USD99.99

You can also pass a custom string instead of 'symbol' or 'code' to display custom text.


3. digitsInfo

The digitsInfo parameter allows you to control the number formatting pattern. It follows the structure:

minIntegerDigits.minFractionDigits-maxFractionDigits

Example:

<p>{{ price | currency:'USD':'symbol':'1.2-2' }}</p>

This means:

  • Minimum 1 integer digit before the decimal.
  • Minimum 2 decimal digits.
  • Maximum 2 decimal digits.

If the number is 99.9, it will display as $99.90.
If the number is 99.999, it will round to $100.00.


4. locale

The locale parameter defines which locale rules to use for formatting. For example, en-US, fr-FR, or ur-PK.

Example:

<p>{{ price | currency:'PKR':'symbol':'1.2-2':'ur-PK' }}</p>

Output:

Rs99.99

This displays the currency in Pakistani Rupees formatted according to Urdu (Pakistan) locale conventions.


Complete Example

Here’s a complete example showing the use of all parameters.

<p>{{ price | currency:'USD':'symbol':'1.2-2' }}</p>

If price = 99.99, the output will be:

$99.99

If you change it to euros:

<p>{{ price | currency:'EUR':'symbol':'1.2-2' }}</p>

Output:

€99.99

If you use the code instead of symbol:

<p>{{ price | currency:'EUR':'code':'1.2-2' }}</p>

Output:

EUR99.99

Importing the CurrencyPipe

The CurrencyPipe is part of Angular’s CommonModule, which is automatically included in the main AppModule when creating an Angular application.

If you are using a standalone component or a feature module, you may need to import it explicitly.

Example of Importing in a Module

import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { MyComponent } from './my.component';

@NgModule({
  declarations: [MyComponent],
  imports: [CommonModule],
})
export class MyModule {}

Once CommonModule is imported, you can use the currency pipe in your templates.


Using CurrencyPipe in TypeScript Code

While pipes are commonly used in templates, you can also use them programmatically inside your TypeScript code by injecting them as dependencies.

Example

import { CurrencyPipe } from '@angular/common';
import { Component } from '@angular/core';

@Component({
  selector: 'app-demo',
  template: &lt;p&gt;{{ formattedPrice }}&lt;/p&gt;,
  providers: [CurrencyPipe]
})
export class DemoComponent {
  price = 2500;
  formattedPrice: string | null;

  constructor(private currencyPipe: CurrencyPipe) {
this.formattedPrice = this.currencyPipe.transform(this.price, 'USD', 'symbol', '1.2-2');
} }

This will produce the same output as using the pipe in a template but gives you flexibility to use it dynamically inside your component logic.


Working with Dynamic Currency Codes

In applications with international users, currency codes often depend on user preferences or country settings.

Example

<p>{{ amount | currency:selectedCurrency:'symbol':'1.2-2' }}</p>

And in your component:

export class AppComponent {
  amount = 1500;
  selectedCurrency = 'EUR';
}

By changing the value of selectedCurrency, you can automatically display different currencies.


Changing Locale Dynamically

Angular supports multiple locales through its i18n system. If you want to display prices based on user’s region, you can change the locale dynamically.

Step 1: Import the Locale Data

import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';
registerLocaleData(localeFr);

Step 2: Provide Locale in Module

import { LOCALE_ID } from '@angular/core';

@NgModule({
  providers: [{ provide: LOCALE_ID, useValue: 'fr' }]
})
export class AppModule {}

Now, all currency values will display using French conventions.


Locale Differences in Currency Formatting

Different locales use different conventions for displaying currency.

Example Comparison

LocaleCodeExample Output
en-USUSD$1,000.00
en-GBGBP£1,000.00
fr-FREUR1 000,00 €
ur-PKPKRRs1,000.00

This difference demonstrates the importance of locale when formatting numbers. The CurrencyPipe handles these differences automatically when configured correctly.


Custom Currency Symbols

You can also define your own display text or symbols instead of the standard currency symbol or code.

Example

<p>{{ price | currency:'USD':'US Dollars':'1.2-2' }}</p>

Output:

US Dollars99.99

This is useful when you want to display currency text differently from the system’s default symbol.


Rounding and Fraction Digits

The CurrencyPipe automatically rounds numbers based on the digits information you provide.

Example

<p>{{ value | currency:'USD':'symbol':'1.0-0' }}</p>

If the value is 1234.56, it will display as $1,235 because no decimal digits are allowed.

If you specify '1.2-4', it means a minimum of two and maximum of four decimal digits.

<p>{{ value | currency:'USD':'symbol':'1.2-4' }}</p>

For 1234.5678, it displays $1,234.5678.


Handling Null or Undefined Values

Sometimes, the value passed to the pipe may be null or undefined, especially before asynchronous data is loaded.

Safe Example

<p>{{ price ? (price | currency:'USD') : 'Loading...' }}</p>

This prevents errors and ensures that your template remains stable even if the value is temporarily undefined.


Using CurrencyPipe with Reactive Forms

You can format numeric form values using the CurrencyPipe in conjunction with Angular forms.

Example

import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';

@Component({
  selector: 'app-form-currency',
  template: `
&lt;input type="number" &#91;formControl]="priceControl" /&gt;
&lt;p&gt;{{ priceControl.value | currency:'USD':'symbol':'1.2-2' }}&lt;/p&gt;
` }) export class FormCurrencyComponent { priceControl = new FormControl(0); }

When you update the input, the displayed value updates immediately in formatted currency style.


Displaying Prices in Lists and Tables

In e-commerce or admin dashboards, it’s common to use CurrencyPipe inside ngFor loops.

Example

<table>
  <tr *ngFor="let item of items">
&lt;td&gt;{{ item.name }}&lt;/td&gt;
&lt;td&gt;{{ item.price | currency:'USD':'symbol':'1.2-2' }}&lt;/td&gt;
</tr> </table>

Component

export class ProductListComponent {
  items = [
{ name: 'Laptop', price: 999.99 },
{ name: 'Phone', price: 499.49 },
{ name: 'Headphones', price: 89.99 }
]; }

This makes it easy to display a well-formatted price list without extra logic.


Using CurrencyPipe with Async Data

When working with APIs, data is often loaded asynchronously.

Example

<p *ngIf="price$ | async as price">
  {{ price | currency:'USD':'symbol':'1.2-2' }}
</p>

Component

import { Component } from '@angular/core';
import { of } from 'rxjs';
import { delay } from 'rxjs/operators';

@Component({
  selector: 'app-async-currency',
  templateUrl: './async-currency.component.html'
})
export class AsyncCurrencyComponent {
  price$ = of(123.45).pipe(delay(1000));
}

This pattern works perfectly with observables and keeps templates clean.


Real-World Use Cases

1. Shopping Cart Totals

<p>Total: {{ totalAmount | currency:'USD':'symbol':'1.2-2' }}</p>

2. Displaying Multi-Currency Data

<p>{{ product.price | currency:product.currency:'symbol':'1.2-2' }}</p>

3. Invoice Generation

<p>Subtotal: {{ subtotal | currency:'USD' }}</p>
<p>Tax: {{ tax | currency:'USD' }}</p>
<p>Total: {{ total | currency:'USD' }}</p>

4. Financial Dashboards

<p>Revenue: {{ revenue | currency:'EUR':'symbol':'1.2-2' }}</p>
<p>Expenses: {{ expenses | currency:'EUR':'symbol':'1.2-2' }}</p>

5. Salary Management Systems

<p>Employee Salary: {{ salary | currency:'PKR':'symbol':'1.0-0' }}</p>

CurrencyPipe in Standalone Components

If you’re using Angular standalone components, you can use CurrencyPipe by importing CommonModule in the component’s imports array.

Example

import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'app-currency-demo',
  standalone: true,
  imports: [CommonModule],
  template: &lt;p&gt;{{ 5000 | currency:'USD':'symbol' }}&lt;/p&gt;
})
export class CurrencyDemoComponent {}

Performance Considerations

Using pipes in templates is efficient because Angular only re-evaluates them when input values change. However, when dealing with large lists, use pure pipes wisely. CurrencyPipe is a pure pipe, meaning it runs only when data changes. This ensures good performance even in large data tables.


Formatting Multiple Locales

If your app supports multiple languages, you can register multiple locales and switch between them.

Example

import { registerLocaleData } from '@angular/common';
import localeEn from '@angular/common/locales/en';
import localeDe from '@angular/common/locales/de';

registerLocaleData(localeEn);
registerLocaleData(localeDe);

Then provide locale dynamically.

@NgModule({
  providers: [{ provide: LOCALE_ID, useValue: 'de' }]
})
export class AppModule {}

Now, your currency will appear using German locale formatting.


Troubleshooting Common Issues

  1. Error: Missing locale data for the locale.
    • Register the locale using registerLocaleData.
  2. Currency symbol not showing correctly.
    • Check if you used 'symbol' as the display parameter.
  3. Unexpected number of decimals.
    • Verify your digitsInfo parameter.
  4. Service not found error in TypeScript.
    • If using programmatically, ensure CurrencyPipe is added to the component’s providers array.

CurrencyPipe vs DecimalPipe

The CurrencyPipe is built on top of the DecimalPipe but adds features like currency symbols and locale-based formatting.

Example with DecimalPipe:

<p>{{ value | number:'1.2-2' }}</p>

Example with CurrencyPipe:

<p>{{ value | currency:'USD':'symbol':'1.2-2' }}</p>

The CurrencyPipe is ideal when representing monetary data, while DecimalPipe is better for general numerical values.


Unit Testing CurrencyPipe

When writing tests for components that use CurrencyPipe, you can either test the raw pipe output or rely on snapshot testing.

Example

import { CurrencyPipe } from '@angular/common';

describe('CurrencyPipe', () => {
  it('should format number as USD', () => {
const pipe = new CurrencyPipe('en-US');
expect(pipe.transform(100, 'USD')).toBe('$100.00');
}); });

This ensures consistent currency formatting across your app.


Combining CurrencyPipe with Other Pipes

You can chain multiple pipes in Angular templates.

Example

<p>{{ price | currency:'USD':'symbol':'1.2-2' | uppercase }}</p>

Output:

$99.99 → $99.99 (uppercase doesn’t change symbols but affects text when applicable)

You can also combine it with async or conditional pipes for complex templates.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *