DEV Community

Cover image for Human-readable Numbers
Thomas Rigby
Thomas Rigby

Posted on

1

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! 😎

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Cloudinary image

Zoom pan, gen fill, restore, overlay, upscale, crop, resize...

Chain advanced transformations through a set of image and video APIs while optimizing assets by 90%.

Explore

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay