@zohodesk/utils
Version:
DOT Utils Collection
44 lines (36 loc) • 1.15 kB
JavaScript
/**
*
* @param {number|string} count
* @param {object} options
* @param {string} options.locale
* @param {boolean} options.withAbbr
* @param {number} options.decimals
* @returns
*/
export default function abbreviateNumber() {
let count = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if (typeof count === 'string') {
count = parseInt(count);
}
if (global.Intl && global.Intl.NumberFormat) {
let numberFormat = Intl.NumberFormat(options.locale || 'en', {
notation: 'compact' // compactDisplay: "short",
});
return numberFormat.format(count);
} //Comaptibility
const COUNT_ABBRS = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'];
let {
withAbbr = true,
decimals = 2
} = options;
const i = 0 === count ? count : Math.floor(Math.log(count) / Math.log(1000));
let result = parseFloat((count / Math.pow(1000, i)).toFixed(decimals));
if (withAbbr) {
result += `${COUNT_ABBRS[i]}`;
}
return result;
}
/* need discussion
1001 => 1K+
G, T, P, E, Z,Y are needed in practical */