Categories
JavaScript Answers

How to Format a Number with K at the End if it is One Thousand or More and Show the Number Otherwise in JavaScript?

Spread the love

Sometimes, we want to format a number so that we show K at the end if it’s a thousand or more and return the show number if it’s less than 1000.

In this article, we’ll look at how to format a number with K at the end if it’s 1000 or more and return the whole number otherwise.

Use Math Methods

We can create our own function that use Math methods to check if a number is 1000 or bigger in absolute value.

If it is, then we divide by 1000 and add a K after it.

Otherwise, we return the whole number.

To do this, we write:

const kFormatter = (num) => {
  return Math.abs(num) > 999 ? Math.sign(num) * ((Math.abs(num) / 1000).toFixed(1)) + 'k' : Math.sign(num) * Math.abs(num)
}

console.log(kFormatter(1200));
console.log(kFormatter(-1200));
console.log(kFormatter(900));
console.log(kFormatter(-900));

We create the kFormatted function that takes the num number parameter.

Then we check if num is bigger than 999 in absolute value.

Math.abs lets us compute the absolute value of a number.

If it’s bigger than 999, then we use Math.sign to get the sign of the number.

Math.sign return -1 if the number is negative and 1 otherwise.

Then we multiply that by the absolute value of num divided by 1000.

And then we call toFixed with 1 to return a string version of the number rounded to one decimal place.

Then we add 'k' after it.

Otherwise, we just return the number itself with:

Math.sign(num) * Math.abs(num)

So we get:

1.2k
-1.2k
900
-900

from the console log results.

Conclusion

We can use various Math methods to format numbers to return a truncated number if it’s 1000 or more and return the whole number otherwise.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *