Explain Codes LogoExplain Codes Logo

Format a number as 2.5K if a thousand or more, otherwise 900

javascript
formatting
number-formatting
intl-number-format
Alex KataevbyAlex Kataev·Oct 21, 2024
TLDR

If you're in a rush and want a quick solution to format numbers in JavaScript, use a ternary operator for a one-liner. If the number is >= 1000, divide it by 1000 and append 'K'; else, leave the number as it is.

const formatNum = n => n >= 1000 ? `${(n / 1000).toFixed(1)}K` : `${n}`;

Call the function like so:

console.log(formatNum(2500)); // "2.5K" - As they say in bowling, "Steee-rike!" console.log(formatNum(900)); // "900" - You can't K this. It's too small to K.

Advanced formatting on the fly

Sometimes, "K-ing" numbers might not be enough for you, especially if you're dealing with international users. In this case, use the hot-shot Intl.NumberFormat object with 'compact' notation for slick, locale-aware formatting.

const internationalFormatNum = (n) => new Intl.NumberFormat('en', { notation: 'compact', maximumFractionDigits: 1 }).format(n);

This function takes care of both small or large numbers. Neat, right? However, do ensure compatibility as not all environments support it yet.

Magnitude-based formatting: a more rockstar way

The regular K, M, G suffixes might feel too "last century" for you, and you want a more sophisticated way of commuting this. Fret not. Using Math.log10 and a SI_SYMBOL array, you can bring out your inner rockstar with this scale-focused formatter.

const abbreviateNumber = (value) => { const SI_SYMBOL = ["", "K", "M", "G", "T", "P", "E"]; const tier = Math.log10(Math.abs(value)) / 3 | 0; if(tier == 0) return value.toString(); const suffix = SI_SYMBOL[tier]; const scale = Math.pow(10, tier * 3); const scaled = value / scale; return scaled.toFixed(1) + suffix; }

Poof! Watch 1000 become 1.0K or 1.0E for 10^18.

Zeros-Be-Gone formatting: clean as a whistle

Cluttered display? Unwanted .0? Zeros be gone with this variant that employs a-simple-pimple .replace() method.

const formatNumClean = n => (n / 1000).toFixed(1).replace(/\.0+$/, "") + 'K';

This code tidies your number formatting by removing trailing zeroes after the decimal. So, 2000 becomes a clean and crisp 2K instead of a cluttered 2.0K.

Cook-Book: some handy recipes

Here are a few rank and file test recipes you can use with different number ranges for more robust implementation. That's right, we're stress testing these babies!

console.log(formatNum(999)); // "999" console.log(formatNum(1000)); // "1.0K" console.log(formatNum(1999)); // "2.0K" console.log(formatNum(19999)); // "20.0K" console.log(formatNum(999999)); // "1.0M"

Things that make you go "Hmm"

The solutions above are pretty neat, but as you know: an ounce of prevention is worth a pound of cure. Let's ponder on these things that might make you go "Hmm":

  • Use Math.sign() and Math.abs() to keep the peace (sign peace, that is) while formatting.
  • Ensure localization support or consider a backup plan.
  • "G" for "Billion" or "B" for Billion? Know your locale preferences.
  • Can't find Intl.NumberFormat support? Consider a polyfill. You know, just in case.