diff --git a/package.json b/package.json index 284bfef..cdecb26 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@platformbuilders/helpers", - "version": "0.2.3", + "version": "0.2.4", "description": "Platfom builders helpers library", "main": "dist/index.js", "types": "dist/index.d.ts", diff --git a/src/__tests__/currencyParser.spec.ts b/src/__tests__/currencyParser.spec.ts index dbe78c2..f715165 100644 --- a/src/__tests__/currencyParser.spec.ts +++ b/src/__tests__/currencyParser.spec.ts @@ -6,6 +6,10 @@ describe('currencyParser tests', () => { const parsed = currencyParser('abc'); expect(parsed).toBe('R$ 0,00'); }); + it('should format currency properly if value has only letters and consider number of decimals', () => { + const parsed = currencyParser('abc', 0); + expect(parsed).toBe('R$ 0'); + }); it('should format currency properly if value has letters and numbers', () => { const parsed = currencyParser('1k'); diff --git a/src/currencyParser.ts b/src/currencyParser.ts index 6cf6a2d..f8e7c76 100644 --- a/src/currencyParser.ts +++ b/src/currencyParser.ts @@ -5,6 +5,7 @@ export const currencyParser = ( value: string | number, numberOfDecimalPlaces = NUMBER_OF_DECIMAL_PLACES_DEFAULT, ): string => { + let formatValue = value; const isValidValue = regex.test(String(value)); const decimals = numberOfDecimalPlaces < 0 @@ -12,10 +13,10 @@ export const currencyParser = ( : numberOfDecimalPlaces; if (!isValidValue) { - return 'R$ 0,00'; + formatValue = 0; } - const withDecimalValue = Number(value) + const withDecimalValue = Number(formatValue) .toFixed(decimals) .replace('.', ',') .replace(/(\d)(?=(\d{3})+,)/g, '$1.');