📚Cheatsheets

Cheatsheet collection for go, rust, python, shell and javascript.

Format number to 1K or 1M or 1B in JavaScript

To format a number in JavaScript with suffixes like "k" for thousands, "m" for millions, and "b" for billions, you can use the toLocaleString method. Here is an example of how you can use this method to format a number:

var number = 1000000;
// Use the toLocaleString method to add suffixes to the number
var formattedNumber = number.toLocaleString('en-US', {
  // add suffixes for thousands, millions, and billions
  // the maximum number of decimal places to use
  maximumFractionDigits: 2,
});
console.log(formattedNumber); // 1,000,000.00

In this example, the number is first formatted using the toLocaleString method. This method takes two arguments: a locale and an options object.

The locale specifies the language and regional settings to use when formatting the number, and the options object allows you to customize the formatting.

In this case, we set the maximumFractionDigits option to 2, which specifies that the number should be formatted with no more than two decimal places.

You can also use the toLocaleString method to add suffixes to the formatted number. For example, to add "k" for thousands, "m" for millions, and "b" for billions, you can use the following code:

function formatNumber(number) {
  // Use the toLocaleString method to add suffixes to the number
  umber.toLocaleString('en-US', {
    // add suffixes for thousands, millions, and billions
    // the maximum number of decimal places to use
    maximumFractionDigits: 2,
    // specify the abbreviations to use for the suffixes
    notation: 'compact',
    compactDisplay: 'short'
  });
}

In this example, we use the notation and compactDisplay options to specify that the number should be formatted using abbreviations, and that the abbreviations should be short (e.g. "k" for thousands, instead of "thousands").

This will cause the number to be formatted with the appropriate suffix (e.g. "1M" for one million, instead of "1,000,000").

Usage :

formatNumber(1000) // 1K
formatNumber(10000) // 10K
formatNumber(1000000) // 1M