Skip to content

Shorten Count for Large Numbers#

Introduction#

Counting large numbers can be difficult for humans to read. We can add suffix to indicate a measurement or a count.

For example, 1,500,000 views would be easier to read as 1.5M views

We can easily do this by writing a utility function.

Shorten Count#

shorten-count.ts
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
export const shortenCount = (count: number, decimal = 0) => {
  if (isNaN(count)) return null;
  if (count === null) return null;
  if (count === 0) return '-';

  let exp: number;

  const suffixes = ['K', 'M', 'B', 'T', 'Q'];

  if (count < 1000) return count;

  exp = Math.floor(Math.log(count) / Math.log(1000));

  return (count / Math.pow(1000, exp)).toFixed(decimal) + suffixes[exp - 1];
};

Usage#

Anything less than 1000 would return the original number.

shortenCount(500); // -> 500

Breakdown Explanation#

Let's breakdown what happens when we give a number larger than 1000.

Given Count is 567890


Math.log()#

The Math.log() static method returns the natural logarithm (base e) of a number. 1

function getBaseLog(x, y) {
  return Math.log(y) / Math.log(x);
}

// 2 x 2 x 2 = 8
console.log(getBaseLog(2, 8));
// Expected output: 3

// 5 x 5 x 5 x 5 = 625
console.log(getBaseLog(5, 625));
// Expected output: 4

console.log(Math.log(1000));
// 6.907755278982137

console.log(Math.log(567890));
// 13.249683016976556
shorten-count.ts
12
exp = Math.floor(Math.log(567890) / Math.log(1000)); // 1

The output for exp is: 1

We will use the value of exp as a power to raise a base value.


Math.pow()#

The Math.pow() static method returns the value of a base raised to a power. 2

Math.pow(2, 1) // 2
// -> 2

Math.pow(2, 2) // 2 x 2
// -> 4

Math.pow(2, 3) // 2 x 2 x 2
// -> 8

Math.pow(1000, 1) // exp = 1
// -> 1000

567890 / 1000
// -> 567.89
shorten-count.ts
14
return (567.89).toFixed(decimal) + suffixes[exp - 1];

The suffixes[0] would return K

shorten-count.ts
8
const suffixes = ['K', 'M', 'B', 'T', 'Q'];
567.89.toFixed(0) // 568
567.89.toFixed(1) // 567.9

Thus, our output for count 567890 is 568K

shortenCount(count, decimal)

count decimal output
1500000 1 1.5M
567890 0 568K
1234567890 1 1.2B

Conclusion#

Now, as a human, which is easier to read?

Comments