@megaads/wm
Version:
To install the library, use npm:
85 lines (74 loc) • 2.73 kB
text/typescript
import { PriceOptions } from './types';
class Price {
readonly currencyUnit: string;
readonly currencyTemplate: {};
constructor(options: PriceOptions) {
this.currencyUnit = options.currencyUnit;
this.currencyTemplate =
{
'USD': '${money}{.}{2}',
'VND': '{money}{,}{0}₫',
'JPY': '¥{money}{.}{0}',
'EUR': '{money}{,}{2}€',
'GBP': '£{money}{.}{2}',
'CAD': 'CA${money}{.}{2}',
'AUD': 'AU${money}{.}{2}',
'KRW': '₩{money}{,}{0}',
'PLN': '{money}{,}{2}zł'
}
;
}
formatPrice(price: number) {
let template = this.getTemplatePrice();
if (!template) {
return this.formatNumber(price, ',', '.') + ' ₫';
} else {
let retVal = this.formatNumber(price, ',', '.') + ' ₫';
let matches = template.match(/{money}{([^a-zA-z0-9]+)}{([0-9]+)}/);
if (!matches) {
throw new Error('Invalid price template');
}
if (matches.length > 2) {
let separate = matches[1];
let number = parseInt(matches[2]);
template = template.replace(/{([^a-zA-z0-9]+)}/, '');
template = template.replace(/{([0-9]+)}/, '');
let decimal = separate == '.' ? ',' : '.';
retVal = template.replace('{money}', this.formatNumber(price, separate, decimal, number));
}
return retVal;
}
}
private getTemplatePrice() {
// @ts-ignore
return this.currencyTemplate[this.currencyUnit];
}
private formatNumber(price: number, desSep = ',', groupSep = '.', number = 0) {
if (price != parseFloat(String(price))) {
price = 0;
}
let newStr = '';
price = parseFloat(String(price));
const p = price.toFixed(number).split(".");
const chars = p[0].split("").reverse();
let count = 0;
for (let x = 0; x < chars.length; x++) {
count++;
if (count % 3 == 1 && count != 1) {
newStr = chars[x] + groupSep + newStr;
} else {
newStr = chars[x] + newStr;
}
}
if (p.length > 1) {
newStr += desSep + p[1];
} else if (number > 0) {
newStr += desSep;
for (let i = 0; i < number; i++) {
newStr += '0';
}
}
return newStr;
}
}
export default Price;