From 14db3dd9e23cb02e65ea4d598085a61127f5ff2f Mon Sep 17 00:00:00 2001 From: Michael Amaral Date: Thu, 30 Jul 2020 03:26:35 -0300 Subject: [PATCH] fixing currency parse invalid value with decimal arguments --- package.json | 2 +- src/__tests__/currencyParser.spec.ts | 4 ++++ src/currencyParser.ts | 5 +++-- 3 files changed, 8 insertions(+), 3 deletions(-) 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.');