Skip to content

Instantly share code, notes, and snippets.

@justinallen
Last active June 22, 2017 22:44
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 justinallen/a6e1b46948176b9a07a383ee0681499c to your computer and use it in GitHub Desktop.
Save justinallen/a6e1b46948176b9a07a383ee0681499c to your computer and use it in GitHub Desktop.
/**
* 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