number.js 1.9 KB

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