From 8ea7f9bc17624effdaca9aed4a4b760f43eb9235 Mon Sep 17 00:00:00 2001 From: David Sevilla Martin Date: Sat, 7 Mar 2020 10:00:33 -0500 Subject: [PATCH] common: add formatNumber - use toLocaleString and support current application locale + custom options --- js/src/common/utils/formatNumber.ts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 js/src/common/utils/formatNumber.ts diff --git a/js/src/common/utils/formatNumber.ts b/js/src/common/utils/formatNumber.ts new file mode 100644 index 000000000..bd8e6570c --- /dev/null +++ b/js/src/common/utils/formatNumber.ts @@ -0,0 +1,16 @@ +/** + * The `formatNumber` utility localizes a number into a string with the + * appropriate punctuation. + * + * @param number Number to format + * @param options Maximum significant digits or formatting options object + * + * @example + * formatNumber(1234); + * // 1,234 + */ +export default function formatNumber(number: number, options: number | Intl.NumberFormatOptions = {}): string { + const config = typeof options === 'number' ? { maximumSignificantDigits: options } : options; + + return number.toLocaleString(app.translator.locale, config); +}