index.ts (1523B)
1 import { util_rxp } from "../validation/regex.js"; 2 3 export type FiatCurrency = `usd` | `eur`; 4 export const fiat_currencies: FiatCurrency[] = [`usd`, `eur`] as const; 5 6 // @todo 7 export const price_to_formatted = (n: number, _currency: string) => Math.round(n * 100) / 100; 8 9 export const parse_currency = (val?: string): FiatCurrency => { 10 const cur = val?.trim().toLowerCase() 11 switch (cur) { 12 case `usd`: 13 case `eur`: 14 return cur; 15 default: 16 return `usd`; 17 }; 18 }; 19 20 export const fmt_price = (locale: string, value: string, currency: string): string => { 21 const fmt = new Intl.NumberFormat(locale, { 22 style: 'currency', 23 currency: currency.toUpperCase(), 24 minimumFractionDigits: 2, 25 maximumFractionDigits: 2 26 }); 27 return fmt.format(parseFloat(value)); 28 }; 29 30 export const parse_currency_marker = (locale: string, currency: string): string => { 31 const cur = parse_currency(currency); 32 const fmt = new Intl.NumberFormat(locale, { 33 style: 'currency', 34 currency: cur.toUpperCase(), 35 minimumFractionDigits: 2, 36 }); 37 const fmt_basis = fmt.format(1); 38 let fmt_res: string | undefined = undefined; 39 fmt_res = fmt_basis.match(util_rxp.currency_marker)?.[0]; 40 if (fmt_res) return fmt_res; 41 fmt_res = fmt_basis.match(util_rxp.currency_symbol)?.[0]; 42 if (fmt_res) return fmt_res; 43 fmt_res = fmt_basis.match(new RegExp(cur, `i`))?.[0]; 44 if (fmt_res) return fmt_res; 45 return cur.toUpperCase(); 46 };