Skip to content

Commit

Permalink
fix: decimal should auto cut (#813)
Browse files Browse the repository at this point in the history
  • Loading branch information
zombieJ authored Feb 28, 2022
1 parent 8559093 commit 544cb27
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 5 deletions.
7 changes: 4 additions & 3 deletions docs/examples/debug.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,10 @@ export default () => {
}}
// value={value}

min={0.05}
max={2}
step={1}
min={0}
max={1}
defaultValue={0.81}
step={0.01}
/>
</div>
</div>
Expand Down
10 changes: 8 additions & 2 deletions src/hooks/useOffset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,13 @@ export default function useOffset(
(val) => {
if (step !== null) {
const stepValue = min + Math.round((formatRangeValue(val) - min) / step) * step;
return min <= stepValue && stepValue <= max ? stepValue : null;

// Cut number in case to be like 0.30000000000000004
const getDecimal = (num: number) => (String(num).split('.')[1] || '').length;
const maxDecimal = Math.max(getDecimal(step), getDecimal(max), getDecimal(min));
const fixedValue = Number(stepValue.toFixed(maxDecimal));

return min <= fixedValue && fixedValue <= max ? fixedValue : null;
}
return null;
},
Expand Down Expand Up @@ -96,7 +102,7 @@ export default function useOffset(
let nextValue: number;
const originValue = values[valueIndex];

// Used for `dist` mode
// Only used for `dist` mode
const targetDistValue = originValue + offset;

// Compare next step value & mark value which is best match
Expand Down
9 changes: 9 additions & 0 deletions tests/Slider.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -571,4 +571,13 @@ describe('Slider', () => {
expect(onChange).toHaveBeenCalledWith(2);
expect(container.querySelector('.rc-slider-handle').style.left).toBe('100%');
});

it('not show decimal', () => {
const onChange = jest.fn();
const { container } = render(
<Slider min={0} max={1} step={0.01} defaultValue={0.81} onChange={onChange} />,
);
fireEvent.keyDown(container.querySelector('.rc-slider-handle'), { keyCode: keyCode.RIGHT });
expect(onChange).toHaveBeenCalledWith(0.82);
});
});

1 comment on commit 544cb27

@vercel
Copy link

@vercel vercel bot commented on 544cb27 Feb 28, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.