import { Pipe, PipeTransform } from '@angular/core'; // enums import { eStringPlaceholder, eUnit } from '../enums'; @Pipe({ name: 'formatCurrency', standalone: true, }) export class FormatCurrencyPipe implements PipeTransform { transform(currency: number, useAbbreviation?: boolean): string { if (!currency) return eUnit.DOLLAR_SIGN + 0; if (useAbbreviation) return this.nFormatter(currency); return ( eUnit.DOLLAR_SIGN + currency.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,') ); } private nFormatter(num: number): string { const si = [ { value: 1, symbol: eStringPlaceholder.EMPTY }, { value: 1e3, symbol: 'K' }, { value: 1e6, symbol: 'M' }, { value: 1e9, symbol: 'G' }, { value: 1e12, symbol: 'T' }, { value: 1e15, symbol: 'P' }, { value: 1e18, symbol: 'E' }, ]; const decimalPlaces = 2; const regex = /\.0+$|(\.[0-9]*[1-9])0+$/; let index; for (index = si.length - 1; index > 0; index--) { if (num >= si[index].value) break; } return ( eUnit.DOLLAR_SIGN + (num / si[index].value) .toFixed(decimalPlaces) .replace(regex, '$1') + si[index].symbol ); } }