Skip to content

Instantly share code, notes, and snippets.

@tw3
Created August 30, 2018 15:11
Show Gist options
  • Save tw3/d54e0b7859f313019bef91ea5e815d4b to your computer and use it in GitHub Desktop.
Save tw3/d54e0b7859f313019bef91ea5e815d4b to your computer and use it in GitHub Desktop.
Currency pipe for Angular that is i18n friendly, used by my CurrencyInputDirective
import { CurrencyPipe } from '@angular/common';
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'appCurrency'})
export class I18NCurrencyPipe extends CurrencyPipe implements PipeTransform {
constructor() {
// NOTE: This seemingly doesn't change anything, but is required.
super('en');
}
getCurrencySymbol(): string {
return this.transform(0, null, 'symbol', '1.0-0').replace('0', '');
}
transform(value: any, symbol?: any, showSymbol?: 'code' | 'symbol' | 'symbol-narrow', precision?: string): string | null {
const localeDataMap: any = {
'en-US': {
currency: {
symbol: 'USD',
showSymbol: 'symbol',
digits: {
rounded: '1.0-0',
full: '1.2-2'
}
}
}
};
const chosenLocal: any = localeDataMap['en-US'];
// NOTE: Set some defaults that match angular and/or use our defaults from the settings service, if we don't hard code a specific case
// NOTE: In general an empty string pulls our default from the settings service and no params => $1.23
symbol = (symbol) ? symbol : chosenLocal.currency.symbol;
showSymbol = (showSymbol == null) ? chosenLocal.currency.showSymbol : showSymbol;
precision = (precision == null) ? null : (precision !== '') ? precision : chosenLocal.currency.digits.full;
return super.transform(value, symbol, showSymbol, precision);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment