DEV Community

Cover image for Human-readable Numbers
Thomas Rigby
Thomas Rigby

Posted on

Human-readable Numbers

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
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

So, using our example from before…

  const valueA = 12300
  const valueB = 45.67
  const numberToDisplay = humanReadableNumber(valueA + valueB) // 12,345.67
Enter fullscreen mode Exit fullscreen mode

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

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

Top comments (0)