Abbreviate number
Want to shorten a number like 34,000 to 34K? Use this vanilla JavaScript utility function to abbreviate a large number and set the number of decimal places.
const abbrNum = (number, decPlaces) => {// 2 decimal places => 100, 3 => 1000, etcdecPlaces = Math.pow(10, decPlaces)// Enumerate number abbreviationsvar abbrev = ['k', 'm', 'b', 't']// Go through the array backwards, so we do the largest firstfor (var i = abbrev.length - 1; i >= 0; i--) {// Convert array index to "1000", "1000000", etcvar size = Math.pow(10, (i + 1) * 3)// If the number is bigger or equal do the abbreviationif (size <= number) {// Here, we multiply by decPlaces, round, and then divide by decPlaces.// This gives us nice rounding to a particular decimal place.number = Math.round((number * decPlaces) / size) / decPlaces// Handle special case where we round up to the next abbreviationif (number == 1000 && i < abbrev.length - 1) {number = 1i++}// Add the letter for the abbreviationnumber += abbrev[i]// We are done... stopbreak}}return number}
How to use
The function takes two arguments: the number you want to shorten and the number of decimal places you want the number to have. For example, abbrNum(34549,0)
would return 34k
and abbrNum(34549,1)
would return 34.5k
.