Embedding the formatting of currencies, dates and much more in i18next
Sébastien Belzile
Posted on July 22, 2021
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$.
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 });
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),
},
Then, in your code:
t("This will be {{ amount, currency }}.", { amount: 12 })
This should format the currency properly.
💖 💪 🙅 🚩
Sébastien Belzile
Posted on July 22, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.