A function named toCurrency
has been created for converting strings or numbers to locale-specific formats:
function toCurrency(
value: string | number,
locale: string = "en-US",
currency: string = "USD",
options?: Intl.NumberFormatOptions
) {
return Number(value).toLocaleString(locale, {
maximumFractionDigits: 2,
style: "currency",
currency: currency,
...options,
});
}
There is also a test suite designed to validate this function:
describe("toCurrency", () => {
test("toCurrency defined", async () => {
expect(toCurrency).toBeDefined();
});
test("toCurrency conversion with pt-BR locale and BRL currency", () => {
const result = toCurrency(1, "pt-BR", "BRL");
expect(result).toEqual("R$ 1,00");
});
test("toCurrency conversion with en-US locale and USD currency", () => {
const result = toCurrency(1, "en-US", "USD");
expect(result).toEqual("$1.00");
});
});
However, the tests are failing specifically when using the pt-BR locale: