DEV Community

Sébastien Belzile
Sébastien Belzile

Posted on • Edited on

1

Embedding the formatting of currencies, dates and much more in i18next

Formatting currencies is a common problem. Let's say you are working on a website that supports multiple language, and is active in multiple countries. One of the problems that you will face is formatting an amount with a currency in a string that contains text. Example:

En: This will be $7.99.
Fr: This will be 7,99$.
Enter fullscreen mode Exit fullscreen mode

Valid solution

One way of solving this problem is to have 2 distinct processes and call them one by one:

const amount: number = 7.99;
const formattedAmount = toCurrency(amount);
t("This will be {{ amount }}", { amount: formattedAmount });
Enter fullscreen mode Exit fullscreen mode

This solution valid, but it could be nice to delegate this boilerplate to i18next.

i18next solution

Interpolation in i18next accepts a format function that can be implemented to handle formatting.

In your configuration:

interpolation: {
  escapeValue: false,
  // Add this line
  format: (value, format) => (format === "currency" ? toCurrency(value) : value),
},
Enter fullscreen mode Exit fullscreen mode

Then, in your code:

t("This will be {{ amount, currency }}.", { amount: 12 })
Enter fullscreen mode Exit fullscreen mode

This should format the currency properly.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (1)

Collapse
 
sbelzile profile image
Sébastien Belzile

Indeed, thanks for adding the actual currency formatting implementation part!

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

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

Okay