From aed078724557488a18d9897684913cc43ed99635 Mon Sep 17 00:00:00 2001 From: darialari Date: Fri, 1 Nov 2024 11:45:30 +0300 Subject: [PATCH] fix(NumberInput): add rounding calculation result to step precision --- .../lab/NumberInput/__tests__/NumberInput.test.tsx | 2 +- src/components/lab/NumberInput/utils.ts | 11 +++++++++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/src/components/lab/NumberInput/__tests__/NumberInput.test.tsx b/src/components/lab/NumberInput/__tests__/NumberInput.test.tsx index b4f9399bc3..859360ba67 100644 --- a/src/components/lab/NumberInput/__tests__/NumberInput.test.tsx +++ b/src/components/lab/NumberInput/__tests__/NumberInput.test.tsx @@ -113,7 +113,7 @@ describe('NumberInput input', () => { it('removes redundant zeros on blur', async () => { const handleUpdate = jest.fn(); - render(); + render(); const input = getInput(); input.focus(); fireEvent.change(getInput(), {target: {value: '00001.10000'}}); diff --git a/src/components/lab/NumberInput/utils.ts b/src/components/lab/NumberInput/utils.ts index a0d58375c6..d8afacf30d 100644 --- a/src/components/lab/NumberInput/utils.ts +++ b/src/components/lab/NumberInput/utils.ts @@ -119,7 +119,8 @@ export function clampToNearestStepValue({ }) { const base = originalMin || 0; const min = originalMin ?? Number.MIN_SAFE_INTEGER; - let clampedValue = value; + let clampedValue = toFixedNumber(value, step); + if (clampedValue > max) { clampedValue = max; } else if (clampedValue < min) { @@ -150,7 +151,8 @@ export function clampToNearestStepValue({ return greaterPossibleValue; } } - return clampedValue; + + return toFixedNumber(clampedValue, step); } export function updateCursorPosition( @@ -201,3 +203,8 @@ export function areStringRepresentationOfNumbersEqual(v1: string, v2: string) { } return false; } + +function toFixedNumber(value: number, baseStep: number): number { + const stepDecimalDigits = baseStep.toString().split('.')[1]?.length || 0; + return parseFloat(value.toFixed(stepDecimalDigits)); +}