Skip to content

Commit

Permalink
- Fix #817, wrong caret position getting set when . is pressed on emp…
Browse files Browse the repository at this point in the history
…ty value and fixedDecimalScale is set.
  • Loading branch information
s-yadav committed Feb 25, 2024
1 parent 0a2018e commit d441c95
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 13 deletions.
29 changes: 17 additions & 12 deletions src/utils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -193,18 +193,23 @@ export function roundToPrecision(numStr: string, scale: number, fixedDecimalScal
const floatValueStr =
afterDecimal.length <= scale ? `0.${afterDecimal}` : floatValue.toFixed(scale);
const roundedDecimalParts = floatValueStr.split('.');
const intPart = beforeDecimal
.split('')
.reverse()
.reduce((roundedStr, current, idx) => {
if (roundedStr.length > idx) {
return (
(Number(roundedStr[0]) + Number(current)).toString() +
roundedStr.substring(1, roundedStr.length)
);
}
return current + roundedStr;
}, roundedDecimalParts[0]);
let intPart = beforeDecimal;

// if we have cary over from rounding decimal part, add that on before decimal
if (beforeDecimal && Number(roundedDecimalParts[0])) {
intPart = beforeDecimal
.split('')
.reverse()
.reduce((roundedStr, current, idx) => {
if (roundedStr.length > idx) {
return (
(Number(roundedStr[0]) + Number(current)).toString() +
roundedStr.substring(1, roundedStr.length)
);
}
return current + roundedStr;
}, roundedDecimalParts[0]);
}

const decimalPart = limitToScale(roundedDecimalParts[1] || '', scale, fixedDecimalScale);
const negation = hasNegation ? '-' : '';
Expand Down
31 changes: 30 additions & 1 deletion test/library/keypress_and_caret.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,36 @@ describe('Test keypress and caret position changes', () => {
expect(input.selectionStart).toEqual(2);
});

it('should put correct position when . is pressed on empty value #817', async () => {
const Test = () => {
const [value, setValue] = useState();
return (
<NumericFormat
autoComplete="off"
fixedDecimalScale
decimalScale={2}
onValueChange={(obj) => {
setValue(obj.value);
}}
value={value}
allowNegative={false}
allowLeadingZeros={false}
/>
);
};

const { input } = await render(<Test />);
simulateNativeKeyInput(input, '.5', 0, 0);

expect(input.selectionStart).toEqual(2);

input.blur();

await wait(0);

expect(input.value).toEqual('0.50');
});

it('should handle caret position correctly when suffix starts with space and allowed decimal separator is pressed. #725', async () => {
const { input } = await render(
<NumericFormat
Expand Down Expand Up @@ -197,7 +227,6 @@ describe('Test keypress and caret position changes', () => {
/>,
);


await userEvent.type(input, '91');

expect(input.value).toEqual('91 people');
Expand Down

0 comments on commit d441c95

Please sign in to comment.