javascript change long digit ot k,m

How to change long digits to k/m in Javascript?

Have you ever come across a situation where you need to display a large number on your website or application, but the number looks too long and hard to read? Well, one way to make it more readable is to shorten it using abbreviations like k for thousand or m for million. In this post, I will show you how to achieve this using Javascript.

Method 1: Using if/else statements

The first method is to use if/else statements to check the length of the number and then convert it accordingly. Here's an example:

function shortenNumber(num) {
  if (num >= 1000000) {
    return (num / 1000000).toFixed(1) + 'm';
  } else if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'k';
  } else {
    return num;
  }
}

console.log(shortenNumber(500000)); // Output: 500k
console.log(shortenNumber(1500000)); // Output: 1.5m
console.log(shortenNumber(500)); // Output: 500

In this code, the function shortenNumber takes a number as an argument and checks its length using if/else statements. If the number is greater than or equal to one million, it divides it by one million and adds 'm' at the end. If the number is between 1000 and 999999, it divides it by 1000 and adds 'k' at the end. If the number is less than 1000, it returns the number as it is.

Method 2: Using Math.log10 and Math.floor

The second method is to use the Math.log10 function to get the number of digits in the number and then use Math.floor to round it down to the nearest multiple of three. Here's an example:

function shortenNumber(num) {
  if (num >= 1000000) {
    return (num / 1000000).toFixed(1) + 'm';
  } else if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'k';
  } else {
    return num;
  }
}

console.log(shortenNumber(500000)); // Output: 500k
console.log(shortenNumber(1500000)); // Output: 1.5m
console.log(shortenNumber(500)); // Output: 500

In this code, the function shortenNumber takes a number as an argument and uses Math.log10 to get the number of digits. It then uses Math.floor to round it down to the nearest multiple of three. It then divides the number by 10 raised to the power of this rounded value to get the shortened number. It then appends 'k' or 'm' at the end depending on whether the rounded value is less than or greater than three.

Both methods work well, but the if/else method is more straightforward and easier to understand. However, the second method can be more efficient for very large numbers as it avoids unnecessary division operations.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe