Skip to content

Instantly share code, notes, and snippets.

@bartwttewaall
Last active September 23, 2019 09:13
Show Gist options
  • Save bartwttewaall/878a70390f2490d2582f9dd47ddde99d to your computer and use it in GitHub Desktop.
Save bartwttewaall/878a70390f2490d2582f9dd47ddde99d to your computer and use it in GitHub Desktop.
import { Component, Input } from '@angular/core';
const currencyPattern = /^([\D\s]+?)(?=[+-\d])/;
const trailingZeroesPattern = /(,|.)00$/;
@Component({
selector: 'price',
template: '{{ formattedPrice }}',
styles: [':host { vertical-align: middle; }']
})
export class PriceComponent {
@Input()
price: number = 0;
@Input()
multiplier: number = 0.01;
@Input()
locale: string = 'nl-NL';
@Input()
currencyCode: string = 'EUR';
@Input()
showCurrencySign: boolean = true;
@Input()
useShorthand: boolean = false;
get formattedPrice(): string {
return this.toCurrencyString(this.price * this.multiplier, this.showCurrencySign, this.useShorthand);
}
toCurrencyString(price: number, showCurrencySign: boolean = true, useShorthand: boolean = true): string {
let currencyString = price.toLocaleString(this.locale, { currency: this.currencyCode, style: 'currency' });
if (!showCurrencySign) currencyString = currencyString.replace(currencyPattern, '');
if (useShorthand) currencyString = currencyString.replace(trailingZeroesPattern, '$1-');
return currencyString;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment