Last active
December 25, 2018 10:12
-
-
Save productioncoder/64a9faa21e49177a06bd1a82c08e974b to your computer and use it in GitHub Desktop.
Display a large number in a concise way
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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