diff --git a/.changeset/warm-yaks-admire.md b/.changeset/warm-yaks-admire.md new file mode 100644 index 0000000000..69750efc3b --- /dev/null +++ b/.changeset/warm-yaks-admire.md @@ -0,0 +1,5 @@ +--- +'@commercetools-uikit/money-input': patch +--- + +Add support for negative numbers. diff --git a/packages/components/inputs/money-input/src/money-input.spec.js b/packages/components/inputs/money-input/src/money-input.spec.js index b5b424abf2..43e6e1c651 100644 --- a/packages/components/inputs/money-input/src/money-input.spec.js +++ b/packages/components/inputs/money-input/src/money-input.spec.js @@ -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(); + + // 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 diff --git a/packages/components/inputs/money-input/src/money-input.tsx b/packages/components/inputs/money-input/src/money-input.tsx index a5a02d0c4f..787296fd48 100644 --- a/packages/components/inputs/money-input/src/money-input.tsx +++ b/packages/components/inputs/money-input/src/money-input.tsx @@ -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);