diff --git a/src/utils.tsx b/src/utils.tsx index b6ac369b..522cc288 100644 --- a/src/utils.tsx +++ b/src/utils.tsx @@ -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 ? '-' : ''; diff --git a/test/library/keypress_and_caret.spec.js b/test/library/keypress_and_caret.spec.js index 1ae35933..0a6843b0 100644 --- a/test/library/keypress_and_caret.spec.js +++ b/test/library/keypress_and_caret.spec.js @@ -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 ( + { + setValue(obj.value); + }} + value={value} + allowNegative={false} + allowLeadingZeros={false} + /> + ); + }; + + const { input } = await render(); + 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( { />, ); - await userEvent.type(input, '91'); expect(input.value).toEqual('91 people');