/ src / utils / number-formatting.ts
number-formatting.ts
 1  /**
 2   * Normalizes and makes sure we include some unicode option for number formating.
 3   */
 4  function localeWithOptionsForNumbers(locale: string) {
 5      locale = locale.toLowerCase().replace('_', '-');
 6  
 7      if (locale === 'hi-in') {
 8          // nu-latn makes the formatter use latin numbers.
 9          // See BCP47 Unicode extensions for number (nu):
10          // http://unicode.org/repos/cldr/trunk/common/bcp47/number.xml
11          // TL;DR -u- means the start of unicode extension.
12          // nu-latn means numeric (nu) extension, latn value
13          return 'hi-in-u-nu-latn';
14      } else if (locale === 'my') {
15          // For the `my` locale, we want to display functional numbers as Latin numerals rather than in Burmese,
16          // so we are overriding the locale to give us the Latin functional numbers. See radar for more context:
17          // rdar://155236306 (LOC: MS-MY: ASOTW | Product Page: Functional: Numbers are not displayed in MS/EN format)
18          return 'my-u-nu-latn';
19      }
20  
21      return locale;
22  }
23  
24  /**
25   * Abbreviate a number into a compact shorthand
26   *
27   * @example
28   * const abbr = abbreviateNumber(10_000, 'en-US'); // '10K'
29   */
30  export function abbreviateNumber(value: number, locale: string): string {
31      const formatter = new Intl.NumberFormat(
32          localeWithOptionsForNumbers(locale),
33          {
34              notation: 'compact',
35          },
36      );
37  
38      return formatter.format(value);
39  }