Skip to content

Commit

Permalink
add formatter option
Browse files Browse the repository at this point in the history
  • Loading branch information
geoperez committed Oct 25, 2023
1 parent a1dfa84 commit 92cb091
Showing 1 changed file with 7 additions and 6 deletions.
13 changes: 7 additions & 6 deletions src/formatter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,25 +9,25 @@ const defaultOptions = <const>{
nullValue: 'N/A',
ignoreUndefined: false,
locale: 'en-US',
currency: 'USD',
};
export const numberFormat = <const>{ style: 'currency', currency: 'USD' };

const internalFotmatter = (
stringData: string,
{
keepFormat,
decimals,
nullValue,
locale,
}: { keepFormat: boolean; decimals: number; nullValue: string; locale: string },
currency,
}: { keepFormat: boolean; decimals: number; nullValue: string; locale: string; currency: string },
format?: FormatTypes,
): string => {
switch (format) {
case 'money': {
const parsedMoney = parseFloat(stringData);
return !parsedMoney
? nullValue
: new Intl.NumberFormat(locale, numberFormat).format(truncate(parsedMoney, 100000));
: new Intl.NumberFormat(locale, { style: 'currency', currency }).format(truncate(parsedMoney, 100000));
}
case 'percentage':
if (decimals === 0) return `${Math.round(parseFloat(stringData))}%`;
Expand Down Expand Up @@ -60,14 +60,15 @@ export const formatter = (
nullValue?: string;
ignoreUndefined?: boolean;
locale?: string;
currency?: string;
},
): string | undefined => {
const { keepFormat, decimals, nullValue, ignoreUndefined, locale } = { ...defaultOptions, ...options };
const { keepFormat, decimals, nullValue, ignoreUndefined, locale, currency } = { ...defaultOptions, ...options };
if (data === undefined && !ignoreUndefined) return undefined;

if (!data && format === 'money') return '$0.00';

return data == null
? nullValue
: internalFotmatter(String(data), { keepFormat, decimals, nullValue, locale }, format);
: internalFotmatter(String(data), { keepFormat, decimals, nullValue, locale, currency }, format);
};

0 comments on commit 92cb091

Please sign in to comment.