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

Step of 0.01 results in too many decimal places in some generated values #131

Open
DanEastBentley opened this issue Nov 18, 2020 · 2 comments

Comments

@DanEastBentley
Copy link

Problem or feature description:

When using step={0.01}, the value generated occasionally has too many decimal places: e.g. 0.47000000000000003 instead of 0.47.

Steps to reproduce (for problems):

Go to https://codesandbox.io/s/pjwwzzj8qm (from https://www.npmjs.com/package/react-compound-slider) and change step={1} to step={0.01}. Move the slider and notice the occasional value with too many decimal places.

Versions (for problems):

React-Compound-Slider:
3.3.1

React:
16.14.0

Browser:
Chrome for Windows 86.0.4240.198

Operating System:
Windows 10 Enterprise, Version 1909

@ralphking
Copy link

Hi @DanEastBentley , did you find an elegant way to mitigate this?

@DanEastBentley
Copy link
Author

DanEastBentley commented Apr 19, 2021

We added this internal callback function:

  const internalFormatTooltip = React.useCallback((value: number) => {
    if (formatTooltip)
      return formatTooltip(value);

    const actualStep = Math.abs(step ?? 1);

    if (Number.isInteger(actualStep))
      return value.toFixed(0);

    const stepString = actualStep.toString();
    const decimalIndex = stepString.indexOf(".");
    const numDecimals = actualStep.toString().length - (decimalIndex + 1);
    return value.toFixed(numDecimals);
  }, [formatTooltip, step]);

formatTooltip & step are props to our Slider component.

  /** Step value. Default is 0.1. */
  step?: number;
  . . .
  /** Format a value for the tooltip */
  formatTooltip?: (value: number) => string;

Refer to internalFormatTooltip whenever you have a formatTooltip prop to a child component of the Slider.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants