ReactHustle

How to convert number to K,M,B format in javascript

Jasser Mark Arioste

Jasser Mark Arioste

How to convert number to K,M,B format in javascript

In this tutorial we will learn how to format numbers using plain javascript like youtube views. 1000 becomes 1k, 1000000 becomes 1m, etc. 

Creating the formatNumber utility function #


export default function formatNumber(num, precision = 2) {
  const map = [
    { suffix: 'T', threshold: 1e12 },
    { suffix: 'B', threshold: 1e9 },
    { suffix: 'M', threshold: 1e6 },
    { suffix: 'K', threshold: 1e3 },
    { suffix: '', threshold: 1 },
  ];

  const found = map.find((x) => Math.abs(num) >= x.threshold);
  if (found) {
    const formatted = (num / found.threshold).toFixed(precision) + found.suffix;
    return formatted;
  }

  return num;
}
123456789101112131415161718

The function accepts two arguments, num which is the number we want to format and the precision of how many decimal places we want. It's a very simple function but there's a lot going on. Let's break it down step by step.

Explanation #

First we create an array of objects to compare the number and determine the suffix. 1e3 is just a more concise way of writing 1000, 1e6 for 1 million and so on.

Next, we find the suffix to be used for the number by comparing it to the threshold from highest to lowest. For example if the number we want to format is 1500. Let's check. Is the number greater than 1 trillion? nope. is the number greater than 1 billion? nope. Is the number greater than 1 million? nope. Is the number greater than 1 thousand? yep. Therefore our suffix is K.

Once we find the suffix we can easily format the number by dividing it to the found threshold, limiting the number of decimal places by using toFixed method and adding the suffix at the end.

If for some reason we don't find anything, we just return the inputted number.

Code in typescript #

If you're using typescript, add the types to the parameters


export default function formatNumber(num:number, precision:number = 1) {
  ... 
}
1234

Usage #


import formatNumber from './formatNumber';

let formatted = formatNumber(1100);
console.log(formatted); //1.1K

formatted = formatNumber(11200);
console.log(formatted); //11.2K
formatted = formatNumber(-11200);
console.log(formatted); //-11.2K
formatted = formatNumber(1110000);
console.log(formatted); //1.1M
formatted = formatNumber(1400000000);
console.log(formatted); //1.4B
formatted = formatNumber(1400000000000, 2);
console.log(formatted); //1.40T
12345678910111213141516

Resources #

If you like tutorials like this, be sure to subscribe to my newsletter below to get updated on awesome tutorials in javascript, react, and web development in general.

Share this post!

Related Posts