Tweak currencyFormat to display currency when it's not USD

This commit is contained in:
Alok Menghrajani
2023-09-21 02:09:40 +02:00
parent bb93ac6bb5
commit 7cf5c4a392

View File

@@ -1,6 +1,15 @@
import { Pipe, PipeTransform } from '@angular/core'; import { Pipe, PipeTransform } from '@angular/core';
import { DecimalPipe } from '@angular/common'; import { DecimalPipe } from '@angular/common';
// Format the currency according to the user's browser locale.
//
// Some currencies share the same symbol (e.g. $ is used for USD and CAN).
// Ideally, the user experience should not be confusing if different accounts
// have conflicting symbols. One solution might be to always show the ISO
// currency code for accounts with mixes currencies. Another solution would be
// to let the user configure how the currency is displayed on a per-currency
// or per-account basis.
@Pipe({ name: 'currencyFormat' }) @Pipe({ name: 'currencyFormat' })
export class CurrencyFormatPipe implements PipeTransform { export class CurrencyFormatPipe implements PipeTransform {
constructor(private decimalPipe: DecimalPipe) { constructor(private decimalPipe: DecimalPipe) {
@@ -11,17 +20,12 @@ export class CurrencyFormatPipe implements PipeTransform {
return ''; return '';
} }
let prefix = amount < 0 ? '-' : ''; // note: we can drop the cast to any if we change the ts target from es5 to es2020 or newer.
return Intl.NumberFormat(navigator.language, {
if(currency === 'USD') { style: "currency",
prefix += '$'; currency,
} minimumFractionDigits: precision,
signDisplay: "negative",
let minDigits = Math.min(2, precision); } as any).format(amount / Math.pow(10, precision));
return prefix +
this.decimalPipe.transform(
Math.abs(amount) / Math.pow(10, precision),
'1.' + minDigits + '-' + precision);
} }
} }