I\'m trying to use pipe to format the price of an item in PT-BR currency format.
Here what i\'m trying to do:
{{statement
Which browser are you using, as stated in the code:
WARNING: this pipe uses the Internationalization API. Therefore it is only reliable in Chrome and Opera browsers. For other browsers please use an polyfill, for example: [https://github.com/andyearnshaw/Intl.js/].
Probably you are best to use another library like the one they mentioned.
I solve....
import { Pipe, PipeTransform } from '@angular/core';
import { CurrencyPipe } from '@angular/common';
@Pipe({
name: 'currencyformat'
})
export class CurrencyFormatPipe implements PipeTransform {
transform(value: number, currencyCode: string = 'BRL', symbolDisplay: boolean = true, digits?: string): string {
if (!value) {
return '';
}
let currencyPipe: CurrencyPipe = new CurrencyPipe('pt-BR');
let newValue: string = currencyPipe.transform(value, currencyCode, symbolDisplay, digits);
return newValue;
}
}
In App.module.ts
import { LOCALE_ID } from '@angular/core';// IMPORTANT
import { registerLocaleData } from '@angular/common';// IMPORTANT
import localePt from '@angular/common/locales/pt';// IMPORTANT
registerLocaleData(localePt); // IMPORTANT
providers: [{
provide: LOCALE_ID,
useValue: "pt-BR"
}],
In your component.html
{{price | currency: 'BRL' }}
Do that:
getFormattedPrice(price: number) {
return new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(price);
}
i solved this way:
import { Pipe, PipeTransform } from '@angular/core';
import { CurrencyPipe } from '@angular/common';
@Pipe({
name: 'currencyFormat'
})
export class CurrencyFormatPipe implements PipeTransform {
transform(value: number, locale: string, currency_symbol: boolean, number_format: string = '1.2-2'): string {
if (value) {
let currencyPipe = new CurrencyPipe();
let new_value: string;
new_value = currencyPipe.transform(value, locale, currency_symbol, number_format);
if (locale = 'BRL') {
new_value = new_value.replace('.', '|').replace(',', '.').replace('|', ',');
}
return new_value
}
}
}
You can set the locale-id. Import the module as follows:
import {LOCALE_ID} from '@angular/core';
And in your module define a provider like this:
providers: [
{
provide: LOCALE_ID,
useValue: "en-US"
}
]
Just exchange for your locale ID (for IDs, refer to the Angular documentation).