Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 formatting currency BRL format

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:

<div class="desc">{{statement.price | currency:'BRL':true:'1.2-2'}} </div>  

The result that i expect is 33.111,00 and now is returning 33,111.00 .

like image 328
Clamorious Avatar asked Aug 03 '16 19:08

Clamorious


People also ask

How would you display currency and currency symbol of a country in angular?

If you want to display your own name instead of default currency symbol you have to pass display parameter. The display parameter can be “code” (currencycode will be displayed) or “symbol” or “symbol-narrow” or any other custom value.

What is the default value of symbolDisplay while using the CurrencyPipe?

The currency pipe has been changed in Angular v5. The symbolDisplay option (third parameter) is now a string instead of a boolean. The accepted values are "code", "symbol" or "symbol-narrow".

What is CurrencyPipe?

CurrencyPipe is used to transform a number to a currency string, formatted according to locale rules that determine group sizing and separator, decimal-point character. Syntax: {{ value | currency }}


2 Answers

I was trying to format my number to Brazilian currency using this pipe

{{p.preco | currency : 'R$' }}

and I had to put the following lines in app.module.ts in order to format the currency correctly (i.e. R$ 12,00)

import {LOCALE_ID, DEFAULT_CURRENCY_CODE} from '@angular/core';
import localePt from '@angular/common/locales/pt';
import {registerLocaleData} from '@angular/common';

registerLocaleData(localePt, 'pt');

@NgModule({
    declarations: [/*...*/],
    imports: [/*...*/],
    providers: [
        {
            provide: LOCALE_ID,
            useValue: 'pt'
        },

        /* if you don't provide the currency symbol in the pipe, 
        this is going to be the default symbol (R$) ... */
        {
            provide:  DEFAULT_CURRENCY_CODE,
            useValue: 'BRL'
        },
    ]
})

It didn't work out until I add the registerLocaleData call

It also works as expected even if you don't provide the currency symbol (R$), you should just call the pipe and angular will look for the DEFAULT_CURRENCY_CODE declared above:

{{p.preco | currency }}

I'm using angular 10, hope it helps!

like image 62
s_bighead Avatar answered Sep 18 '22 14:09

s_bighead


getFormattedPrice(price: number) {
    return new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(price);
}
like image 42
Marcel Avatar answered Sep 16 '22 14:09

Marcel