sghall / react-compound-slider

:black_medium_small_square: React Compound Slider | A small React slider with no opinion on markup or styles
https://react-compound-slider.netlify.com
MIT License
626 stars 80 forks source link

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

Open DanEastBentley opened 3 years ago

DanEastBentley commented 3 years ago

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 commented 3 years ago

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

DanEastBentley commented 3 years ago

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.