Skip to content

Commit

Permalink
fix(NumberInput): add rounding calculation result to step precision
Browse files Browse the repository at this point in the history
  • Loading branch information
DaryaLari committed Nov 5, 2024
1 parent b3496b0 commit aed0787
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ describe('NumberInput input', () => {

it('removes redundant zeros on blur', async () => {
const handleUpdate = jest.fn();
render(<NumberInput allowDecimal onUpdate={handleUpdate} />);
render(<NumberInput allowDecimal step={0.1} onUpdate={handleUpdate} />);
const input = getInput();
input.focus();
fireEvent.change(getInput(), {target: {value: '00001.10000'}});
Expand Down
11 changes: 9 additions & 2 deletions src/components/lab/NumberInput/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -150,7 +151,8 @@ export function clampToNearestStepValue({
return greaterPossibleValue;
}
}
return clampedValue;

return toFixedNumber(clampedValue, step);
}

export function updateCursorPosition(
Expand Down Expand Up @@ -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));
}

0 comments on commit aed0787

Please sign in to comment.