DEV Community

loading...
Cover image for Human-readable Numbers

Human-readable Numbers

thomasxbanks profile image Thomas Banks ・1 min 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
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! 😎

Discussion (0)

Forem Open with the Forem app