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
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 Rigby (@hryggrbyr) on CodePen.
Hope this is as useful for you as it was for me! 😎
Fin
onward-journeys module
Real. Simple. Syndication.
Get my latest content in your favorite RSS reader.
I use InoReader but you don't have to.
Comments
In almost all cases, the comments section is a vile 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 Mastodon (which is not a vile cesspool of Reply Guys, racists, and bots).