number.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. "use strict";
  2. /**
  3. * Represent a number as an integer, percent or currency value
  4. *
  5. * Available in MessageFormat strings as `{VAR, number, integer|percent|currency}`.
  6. * Internally, calls Intl.NumberFormat with appropriate parameters. `currency` will
  7. * default to USD; to change, set `MessageFormat#currency` to the appropriate
  8. * three-letter currency code, or use the `currency:EUR` form of the argument.
  9. *
  10. * @example
  11. * ```js
  12. * var mf = new MessageFormat('en', { currency: 'EUR'});
  13. *
  14. * mf.compile('{N} is almost {N, number, integer}')({ N: 3.14 })
  15. * // '3.14 is almost 3'
  16. *
  17. * mf.compile('{P, number, percent} complete')({ P: 0.99 })
  18. * // '99% complete'
  19. *
  20. * mf.compile('The total is {V, number, currency}.')({ V: 5.5 })
  21. * // 'The total is €5.50.'
  22. *
  23. * mf.compile('The total is {V, number, currency:GBP}.')({ V: 5.5 })
  24. * // 'The total is £5.50.'
  25. * ```
  26. */
  27. Object.defineProperty(exports, "__esModule", { value: true });
  28. exports.numberPercent = exports.numberInteger = exports.numberCurrency = exports.numberFmt = void 0;
  29. var _nf = {};
  30. function nf(lc, opt) {
  31. var key = String(lc) + JSON.stringify(opt);
  32. if (!_nf[key])
  33. _nf[key] = new Intl.NumberFormat(lc, opt);
  34. return _nf[key];
  35. }
  36. function numberFmt(value, lc, arg, defaultCurrency) {
  37. var _a = (arg && arg.split(':')) || [], type = _a[0], currency = _a[1];
  38. var opt = {
  39. integer: { maximumFractionDigits: 0 },
  40. percent: { style: 'percent' },
  41. currency: {
  42. style: 'currency',
  43. currency: (currency && currency.trim()) || defaultCurrency,
  44. minimumFractionDigits: 2,
  45. maximumFractionDigits: 2
  46. }
  47. };
  48. return nf(lc, opt[type] || {}).format(value);
  49. }
  50. exports.numberFmt = numberFmt;
  51. var numberCurrency = function (value, lc, arg) {
  52. return nf(lc, {
  53. style: 'currency',
  54. currency: arg,
  55. minimumFractionDigits: 2,
  56. maximumFractionDigits: 2
  57. }).format(value);
  58. };
  59. exports.numberCurrency = numberCurrency;
  60. var numberInteger = function (value, lc) {
  61. return nf(lc, { maximumFractionDigits: 0 }).format(value);
  62. };
  63. exports.numberInteger = numberInteger;
  64. var numberPercent = function (value, lc) {
  65. return nf(lc, { style: 'percent' }).format(value);
  66. };
  67. exports.numberPercent = numberPercent;