Skip to content

Commit

Permalink
fixing currency parse invalid value with decimal arguments
Browse files Browse the repository at this point in the history
  • Loading branch information
ammichael committed Jul 30, 2020
1 parent 6eb35ec commit 14db3dd
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 3 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
4 changes: 4 additions & 0 deletions src/__tests__/currencyParser.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down
5 changes: 3 additions & 2 deletions src/currencyParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,18 @@ 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
? NUMBER_OF_DECIMAL_PLACES_DEFAULT
: 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.');
Expand Down

0 comments on commit 14db3dd

Please sign in to comment.