Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(Slider): fix floating-point precision issues #18664

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 28 additions & 27 deletions packages/react/src/components/Slider/Slider.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* Copyright IBM Corp. 2016, 2023
* Copyright IBM Corp. 2016, 2025
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
Expand Down Expand Up @@ -635,20 +635,16 @@ class Slider extends PureComponent<SliderProps> {
}

/**
* Takes a value and ensures it fits to the steps of the range
* @param value
* @returns value of the nearest step
* Rounds a given value to the nearest step defined by the slider's `step`
* prop.
*
* @param value - The value to adjust to the nearest step. Defaults to `0`.
* @returns The value rounded to the precision determined by the step.
*/
nearestStepValue(value) {
const tempInput = document.createElement('input');

tempInput.type = 'range';
tempInput.min = `${this.props.min}`;
tempInput.max = `${this.props.max}`;
tempInput.step = `${this.props.step}`;
tempInput.value = `${value}`;
nearestStepValue(value = 0) {
const decimals = (this.props.step?.toString().split('.')[1] || '').length;

return parseFloat(tempInput.value);
return Number(value.toFixed(decimals));
}

/**
Expand Down Expand Up @@ -839,7 +835,11 @@ class Slider extends PureComponent<SliderProps> {
? this.state.value
: this.state.valueUpper;
const { value, left } = this.calcValue({
value: this.calcValueForDelta(currentValue, delta, this.props.step),
value: this.calcValueForDelta(
currentValue ?? this.props.min,
delta,
this.props.step
),
});
this.setValueLeftForHandle(this.state.activeHandle, {
value: this.nearestStepValue(value),
Expand Down Expand Up @@ -1111,21 +1111,22 @@ class Slider extends PureComponent<SliderProps> {
};

/**
* Given the current value, delta and step, calculate the new value.
* Calculates a new slider value based on the current value, a change delta,
* and a step.
*
* @param {number} currentValue
* Current value user is moving from.
* @param {number} delta
* Movement from the current value. Can be positive or negative.
* @param {number} step
* A value determining how much the value should increase/decrease by moving
* the thumb by mouse.
* @param currentValue - The starting value from which the slider is moving.
* @param delta - The amount to adjust the current value by.
* @param step - The step. Defaults to `1`.
* @returns The new slider value, rounded to the same number of decimal places
* as the step.
*/
calcValueForDelta = (currentValue, delta, step = 1) => {
return (
(delta > 0 ? Math.floor(currentValue / step) * step : currentValue) +
delta
);
calcValueForDelta = (currentValue: number, delta: number, step = 1) => {
const base =
delta > 0 ? Math.floor(currentValue / step) * step : currentValue;
const newValue = base + delta;
const decimals = (step.toString().split('.')[1] || '').length;

return Number(newValue.toFixed(decimals));
};

/**
Expand Down
25 changes: 24 additions & 1 deletion packages/react/src/components/Slider/__test__/Slider-test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* Copyright IBM Corp. 2016, 2023
* Copyright IBM Corp. 2016, 2025
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
Expand Down Expand Up @@ -1183,6 +1183,29 @@ describe('Slider', () => {
mouseMove(container.firstChild, { clientX: 1000 });
expect(onRelease).not.toHaveBeenCalled();
});

it("should round the slider's value when using small step values", async () => {
renderTwoHandleSlider({
value: 0,
min: 0,
max: 1,
step: 0.1,
onChange,
});
const leftHandle = screen.getAllByRole('slider')[0];

await userEvent.click(leftHandle);
await userEvent.keyboard('{ArrowRight}');
await userEvent.keyboard('{ArrowRight}');
await userEvent.keyboard('{ArrowRight}');

// Retrieve the last call to `onChange`.
const lastCall = onChange.mock.calls[onChange.mock.calls.length - 1][0];

// Assert that the value was correctly correctly (i.e., not
// 0.30000000000000004).
expect(lastCall.value).toBe(0.3);
});
});
});
});
Loading