UNPKG

@hhgtech/hhg-components

Version:
41 lines (38 loc) 1.43 kB
'use strict'; // SOURCE: https://stackoverflow.com/a/10601315 const abbreviateNumber = (value) => { let newValue = String(value); if (value >= 1000) { const suffixes = ['', 'k', 'm', 'b', 't']; const numLength = ('' + value).length; let suffixNum = Math.floor(numLength / 3); const isThousandNum = numLength === 6; let shortValue; if (isThousandNum) { shortValue = Math.round(value / 1000); } else { for (let precision = 2; precision >= 1; precision--) { shortValue = parseFloat((suffixNum != 0 ? value / Math.pow(1000, suffixNum) : value).toPrecision(precision)); const dotLessShortValue = (shortValue + '').replace(/[^a-zA-Z 0-9]+/g, ''); if (dotLessShortValue.length <= 2) { break; } } } if (shortValue && shortValue % 1 != 0) { shortValue = shortValue.toFixed(1); } else if (isThousandNum && shortValue && shortValue / 1000 >= 1) { suffixNum += 1; shortValue = shortValue / 1000; } newValue = shortValue + (numLength === 6 ? suffixes[suffixNum - 1] : suffixes[suffixNum]); } return newValue; }; exports.abbreviateNumber = abbreviateNumber;