Skip to content
A jumble of foam numbers

Human-readable Numbers

Wednesday, January 20, 2021

At 420 words, this article should take about 2 minutes to read.

I recently came across a situation where I was required to add two numbers before displaying them on the frontend.

Here is a (very) simplistic example…

  const valueA = 12300
  const valueB = 45.67
  const numberToDisplay = valueA + valueB // 12345.67

The trouble was, the client didn't like the way the number was displayed - 12345.67 felt "too computer-y" 😂

I'm old enough to remember having to write a function that counted the number of digits in the string and insert commas (or fullstops) in the relevant places but I thought to myself:

"Hey, it's 2021! JavaScript is better now! There must be an easier way!"

So, a little bit of searching later - Number.prototype.toLocaleString()!!! 🎉

This handy method will convert a given Number into a human-readable String based on a given language.

In this handy utility function, we format the given value based on the lang attribute on the <html/> element unless one is explicitly provided.

const humanReadableNumber = (value, lang = null) => {
  if (!value) return;
  const locale = lang || document.documentElement.lang || 'en'
  const number = parseFloat(value, 10)
  return number.toLocaleString(locale);
}

So, using our example from before…

  const valueA = 12300
  const valueB = 45.67
  const numberToDisplay = humanReadableNumber(valueA + valueB) // 12,345.67

If you want to have a play around, I made a CodePen.

See the Pen Human-readable number by thomas×banks (ツ) (@thomasxbanks) on CodePen.

Hope this is as useful for you as it was for me! 😎

Comments

In almost all cases, the comments section is a cesspool of Reply Guys, racists, and bots.

I don't want to have to deal with that kind of hell so I don't have a comments section.

If you want to continue the conversation, you can always hit me up on Twitter (which is, in it's own way, a vile cesspool of Reply Guys, racists, and bots).

Thomas Banks

Thomas Banks

When I'm not building things for the internet, I take photos of stuff.
Loading Invisible Visible Navigation Close Arrow Info Online Online