How to Format a String Based on a User’s Language
Users expect to see numbers and dates formatted in a familiar way.
For example, in American English currency is formatted like 100.00. In German and many other languages, it’s formatted like 100,00.
Not everyone formats numbers and dates like American users. At a global company like Insider, we need to ensure we present these values as all users see them in their everyday lives.
Unfortunately, internationalization tends to get pushed for other priorities. I made this error myself when rewriting a stock ticker for our Markets Insider site and only became aware of it when our colleagues in Germany pointed out my mistake.
That exchange went a little something like this:
Me: “We’ve looked into this reported alignment issue and can’t reproduce it.”
Them: “I can reproduce it on production right now.”
Me: “I’m looking at production, I don’t see anything wrong with it.”
Them: “Are you looking at it in German?”
Me: “Well, no. I can’t read German.”
Mistakes happen, but as long as we learn and help others, we can grow from them.
Internationalization should be the default
We don’t always consider internationalization for many reasons as developers, but most of what I’ve seen boils down to time and perceived complexity. We’re typically on a deadline, so we need to get things shipped. It’s also not easy to think about another language if you spend your time in only one language, so it can be intimidating to think about implementing.
Thanks to advances in modern web browsers, we can quickly accomplish this.
Let’s see how we can format a number, like currency, with a built-in browser API.
Get the user’s language with the Navigator API
The Navigator API has many more features than just getting the preferred language; here’s a link to learn more about this on MDN.
const language = navigator.language; // us-eng
Use their preferred language to format the string
const language = navigator.language; // us-eng
const relativeValue = 100000;
const relativeString = relativeValue.toLocaleString(language);console.log(relativeString) // 100,000
Additional Configuration Options
With toLocaleString
, we also have some additional configurations.
When formatting currency or something with decimal places we can pass in maximumFractionDigits
to specify how many digits to display, or minimumFractionDigits
to force a decimal even when working with a whole number.
const language = navigator.language; // us-engconst relativeValue = 100000.98332;const relativeString = relativeValue.toLocaleString( language, { maximumFractionDigits: 2 });console.log(relativeString) // 100,000.98
Putting it all together
In summary, we learned how to format strings based on a user's language by:
- Getting the user’s language
- Passing their language to
toLocaleString
- Using the formatted string