Last active
June 22, 2017 22:44
-
-
Save justinallen/a6e1b46948176b9a07a383ee0681499c to your computer and use it in GitHub Desktop.
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
/** | |
* Nicely format large numbers to make them readable: | |
* Billions to one decimal like "$1.3 billion" | |
* Millions to nearest million like "$346 million" | |
* Thousands to nearest thousand like "$144,000" | |
* @param {number} The number to format | |
* @returns {string} Readable string with dollar sign and amount | |
*/ | |
function niceBigNumber(num) { | |
// format billions to one decimal like "$1.3 billion" | |
if (Math.abs(Number(num)) >= 1.0e+9) { | |
var float = Math.abs(Number(num)) / 1.0e+9; | |
num = '$' + float.toFixed(1) + ' billion'; | |
} | |
// format millions to nearest million like "$346 million" | |
else if (Math.abs(Number(num)) >= 1.0e+6) { | |
var float = Math.abs(Number(num)) / 1.0e+6; | |
num = '$' + float.toFixed() + ' million'; | |
} | |
// format thousands to nearest thousand like "$144,000" | |
else if (Math.abs(Number(num)) >= 1.0e+3) { | |
num = '$' + (Math.round(1000*num)/1000).toLocaleString(); | |
} | |
return num; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment