react-spectrum icon indicating copy to clipboard operation
react-spectrum copied to clipboard

fix: round to correct precision when step uses exponential notation

Open lucasweng opened this issue 8 months ago • 1 comments

Closes https://github.com/adobe/react-spectrum/issues/8274

✅ Pull Request Checklist:

  • [x] Included link to corresponding React Spectrum GitHub Issue.
  • [x] Added/updated unit tests and storybook for this change (for new code or code which already has tests).
  • [x] Filled out test instructions.
  • [x] Updated documentation (if it already exists for this component).
  • [x] Looked at the Accessibility Practices for this feature - Aria Practices

📝 Test Instructions:

  • Added tests for roundToStepPrecision.
  • Existing tests should still pass.

🧢 Your Project:

lucasweng avatar May 22 '25 16:05 lucasweng

Hi @lucasweng, thank you for taking the time to look into this!

I believe it would be helpful to add a few more test cases to cover edge scenarios. Specifically, since JavaScript automatically converts very small numbers into exponential notation, it would be great to include a case like 0.0000000231 as a step value. This gets transformed into "2.31e-8", and your current implementation may not handle it correctly—it identifies the dot and treats the value as if it were in standard decimal format.

To simplify things and make the logic more robust, I’d suggest normalizing all numbers to exponential notation upfront. That way, you only need to handle one consistent format.

Here's a snippet that might help—though please double-check it against your requirements and test cases:

function getPrecision(num: number): number {
    const e = num.toExponential();
    const [base, exponent] = e.split('e');
    const [, decimalPart] = base.split('.');
    return decimalPart
      ? decimalPart.length - parseInt(exponent)
      : Math.abs(parseInt(exponent));
  }

scrgl avatar Jun 02 '25 10:06 scrgl