Skip to content

Instantly share code, notes, and snippets.

@productioncoder
Last active December 25, 2018 10:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save productioncoder/64a9faa21e49177a06bd1a82c08e974b to your computer and use it in GitHub Desktop.
Save productioncoder/64a9faa21e49177a06bd1a82c08e974b to your computer and use it in GitHub Desktop.
Display a large number in a concise way
const UNITS = ['K', 'M', 'B', 'T'];
// https://stackoverflow.com/a/28608086/2328833
export function getShortNumberString(number) {
const shouldShowDecimalPlace = UNITS.some((element, index) => {
const lowerBound = Math.pow(1000, index + 1);
const upperBound = lowerBound + lowerBound * 10;
return number > lowerBound && number < upperBound
});
const digits = shouldShowDecimalPlace ? 1 : 0;
for (let i = UNITS.length - 1; i >= 0; i--) {
const decimal = Math.pow(1000, i + 1);
if (number >= decimal) {
return (number / decimal).toFixed(digits) + UNITS[i];
}
}
return number.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment