UNPKG

645 BJavaScriptView Raw
1const NUMBER_REGEX = new RegExp('(\\d+?)(?=(\\d{3})+(?!\\d)|$)', 'g');
2/**
3 * @name formatDecimal
4 * @description Formats a number into string format with thousand separators
5 */
6export function formatDecimal(value, separator = ',') {
7 // We can do this by adjusting the regx, however for the sake of clarity
8 // we rather strip and re-add the negative sign in the output
9 const isNegative = value[0].startsWith('-');
10 const matched = isNegative
11 ? value.substring(1).match(NUMBER_REGEX)
12 : value.match(NUMBER_REGEX);
13 return matched
14 ? `${isNegative ? '-' : ''}${matched.join(separator)}`
15 : value;
16}