My profile picture. My mom says I'm a handsome boy!
← All Posts

JavaScript Formatters

#Code, #Guides, #Web

JavaScript has some excellent formatters in its newer APIs - they're starting to creep into StackOverflow answers, but check these out if you haven't seen them before!

Formatting Numbers

Want to display a numerical value in a more human-readable format? Use Number.prototype.toLocaleString().

numbers.jsjavascript
1const value = 1000000;
2console.log(value.toLocaleString());
3// => "1,000,000"

If you're using numbers with units or currencies, Intl.NumberFormat has you covered.

currency.jsjavascript
1const base = 165000;
2const amount = 195000;
3
4new Intl.NumberFormat("en-US", {
5 style: "currency",
6 currency: "USD",
7 currencySign: "accounting",
8}).format(base - amount);
9// => "($30,000.00)"
10
11new Intl.NumberFormat("en-US", {
12 style: "percent",
13 signDisplay: "exceptZero",
14}).format(base / amount);
15// => "+85%"

Formatting Lists

Want to format a list of options in a readable format? Rails had a great implmentation with humanize, and now JavaScript does too! Check out Intl.ListFormat.

humanize.jsjavascript
1const formatter = new Intl.ListFormat("en", {
2 style: "long",
3 type: "conjunction",
4});
5
6console.log(
7 formatter.format(["Soccer", "Politics", "Video Games", "Programming"])
8);
9// => "Soccer, Politics, Video Games, and Programming"

It even uses the Oxford Comma!

Formatting Dates

Unfortunately, the Date API doesn't do well formatting time or durations - but the good news is that the new Temporal API does! The spec has a fantastic section on formatting. There are a few polyfills available, so you can use Temporal today if you want.