Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
/**
* 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