diff --git a/src/lib/intlFormat.test.ts b/src/lib/intlFormat.test.ts index f38bd8668..f98a47bc1 100644 --- a/src/lib/intlFormat.test.ts +++ b/src/lib/intlFormat.test.ts @@ -82,6 +82,13 @@ describe('intlFormat', () => { it('handles undefined case', () => { expect(currencyFormat(1000, undefined, 'en-US')).toEqual('$1,000'); }); + it('handles empty string case', () => { + expect(currencyFormat(1234.56, '', 'en-GB')).toEqual('US$1,234.56'); + }); + + it('handles an error', () => { + expect(currencyFormat(1234.56, ' ', 'en-GB')).toEqual('1234.56 '); + }); }); describe('different language', () => { diff --git a/src/lib/intlFormat.ts b/src/lib/intlFormat.ts index 79632cfad..4ef35315d 100644 --- a/src/lib/intlFormat.ts +++ b/src/lib/intlFormat.ts @@ -19,12 +19,21 @@ export const currencyFormat = ( ): string => { const amount = Number.isNaN(value) ? 0 : value; const decimal = amount % 1 !== 0; - return new Intl.NumberFormat(locale, { - style: 'currency', - currency: currency ?? 'USD', - minimumFractionDigits: decimal ? 2 : 0, - maximumFractionDigits: decimal ? 2 : 0, - }).format(Number.isFinite(amount) ? amount : 0); + if (!currency) { + currency = 'USD'; + } + try { + return new Intl.NumberFormat(locale, { + style: 'currency', + currency: currency, + minimumFractionDigits: decimal ? 2 : 0, + maximumFractionDigits: decimal ? 2 : 0, + }).format(Number.isFinite(amount) ? amount : 0); + } catch (error) { + // eslint-disable-next-line no-console + console.error(`Error formatting currency: ${error}`); + return `${amount} ${currency}`; + } }; export const dayMonthFormat = (