Skip to content

Commit

Permalink
Add support for negative numbers in MoneyInput component (#2495)
Browse files Browse the repository at this point in the history
* fix(money-input): fix support for negative numbers

* chore: changeset added
  • Loading branch information
CarlosCortizasCT committed Apr 19, 2023
1 parent d20d14e commit 9b8c101
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/warm-yaks-admire.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@commercetools-uikit/money-input': patch
---

Add support for negative numbers.
15 changes: 15 additions & 0 deletions packages/components/inputs/money-input/src/money-input.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -657,6 +657,21 @@ describe('MoneyInput', () => {
expect(screen.getByLabelText('Amount')).toHaveAttribute('value', '12.00');
});

it('should format the amount on blur for negative numbers', () => {
render(<TestComponent />);

// change amount
fireEvent.change(screen.getByLabelText('Amount'), {
target: { value: '-23' },
});

// blur amount
fireEvent.blur(screen.getByLabelText('Amount'));

// input should have the formatted value after blurring
expect(screen.getByLabelText('Amount')).toHaveAttribute('value', '-23.00');
});

// The original currency (EUR) uses 2 fraction digits, whereas the
// next currency (KWD) uses 3 fraction digits.
// We expect the last fraction to get added when changing the value
Expand Down
2 changes: 1 addition & 1 deletion packages/components/inputs/money-input/src/money-input.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,7 @@ export const parseRawAmountToNumber = (rawAmount: string, locale: string) => {
fractionsSeparator = fractionsSeparator === '.' ? '\\.' : fractionsSeparator; // here we escape the '.' to use it as regex
// The raw amount with only one sparator
const normalizedAmount = String(rawAmount)
.replace(new RegExp(`[^0-9${fractionsSeparator}]`, 'g'), '') // we just keep the numbers and the fraction symbol
.replace(new RegExp(`[^-0-9${fractionsSeparator}]`, 'g'), '') // we just keep the numbers and the fraction symbol
.replace(fractionsSeparator, '.'); // then we change whatever `fractionsSeparator` was to `.` so we can parse it as float

return parseFloat(normalizedAmount);
Expand Down

1 comment on commit 9b8c101

@vercel
Copy link

@vercel vercel bot commented on 9b8c101 Apr 19, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.