Skip to content

Commit

Permalink
Merge pull request #987 from CruGlobal/fix-intl-format-error
Browse files Browse the repository at this point in the history
HelpScout 1199960 - Fixing intlFormat.ts error when currency is not defined
  • Loading branch information
dr-bizz authored Aug 2, 2024
2 parents 1b734b6 + 7c2846c commit b77c3de
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
7 changes: 7 additions & 0 deletions src/lib/intlFormat.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down
21 changes: 15 additions & 6 deletions src/lib/intlFormat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = (
Expand Down

0 comments on commit b77c3de

Please sign in to comment.