
Formatting currency in Angular using Intl.NumberFormat
Format currency in Angular with Intl.NumberFormat using Pipe.
When working with Angular, formatting currency is quite a common requirement. The Intl.NumberFormat API provides a robust solution for this task, enabling developers to present numbers in a way that is sensitive to the user’s locale.
Understanding Intl.NumberFormat
The Intl.NumberFormat API is part of the Internationalization API in JavaScript. It allows developers to format numbers, including currencies, according to specific locales. This means that the same numerical value can be displayed differently based on the user’s geographical location, which is crucial for applications that cater to a global audience.
Key features of Intl.NumberFormat
- Locale sensitivity: the object can format numbers based on the locale specified, ensuring that the currency symbol and number format align with local customs.
- Customizable options: developers can customize the formatting options, such as the number of decimal places, currency type, and whether to use a currency symbol or code.
- Ease of use: the API is straightforward, making it easy for developers to implement without extensive boilerplate code.
Implementing currency formatting in Angular
To format currency in an Angular application using the Intl.NumberFormat API we are going to use Angular Pipe.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'currencyFormatter'
})
export class CurrencyFormatterPipe implements PipeTransform {
public transform(value: string, currencyCode: string = 'USD', locale: string = 'en-US'): string {
const convertedValue: number = Number(value);
return new Intl.NumberFormat(locale, {
style: 'currency',
currency: currencyCode
}).format(convertedValue);
}
}Usage example
<p>{{ getPrice() | currencyFormatter }}</p>The CurrencyFormatterPipe takes a string representing a number, a currency code, and a locale as input. It converts the string to a number, then uses the Intl.NumberFormat API to format the number as currency, taking into account the specified currency and locale. The formatted currency string is then returned. This pipe is a clean and reusable way to format currency values in your Angular templates.
Final words
While there is built-in Angular method formatCurrency it may still be valuable to use a custom method, e.g. when your Angular framework version does not support built-in formatCurrency.
Comments