Format a number as 2.5K if a thousand or more, otherwise 900
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.
Call the function like so:
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.
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.
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.
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!
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()
andMath.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.
Was this article helpful?