Skip to content

[number field] Preserve numeric precision while keeping default display formatting - #5040

Merged
atomiks merged 17 commits into
mui:masterfrom
atomiks:claude/heuristic-ramanujan-976212
Jun 15, 2026
Merged

atomiks merged 17 commits into
mui:masterfrom
atomiks:claude/heuristic-ramanujan-976212

Conversation

@atomiks

@atomiks atomiks commented Jun 12, 2026 •

Copy link
Copy Markdown
Contributor

Fixes precision loss in the NumberField numeric pipeline while keeping the existing default display formatting. This is a compatibility-preserving fix: visible text still follows Intl.NumberFormat defaults (e.g. 1.235 for a no-format field), while the stored numeric value no longer loses precision when stepping or on blur.

What was wrong

removeFloatingPointErrors rounded the stored numeric value to 3 fraction digits whenever format had no Intl rounding options. The 3-digit default was accidental: the original code intended a full-precision fallback (... ?? defaultOptions.maximumFractionDigits ?? 20), but new Intl.NumberFormat().resolvedOptions().maximumFractionDigits is 3, so the ?? 20 never applied.

Consequences:

  • step / smallStep finer than 0.001 were silent no-ops at the numeric level: incrementing from 0 by 0.0001 rounded back to 0, so onValueChange never fired and the value never advanced. Native <input type="number" step="0.0001"> works fine.
  • Button increment/decrement always parsed the visible (rounded) input text before stepping, so a value like 1.23456 — displayed as 1.235 — advanced from the rounded 1.235, dropping precision even when the input wasn't dirty.
  • Blur re-parsed the rounded display text and committed it, so a focus/blur with no edits (or a blur after a programmatic change) collapsed the stored value to its displayed precision.

What changed

Numeric pipeline keeps precision (display unchanged)

  • Floating-point cleanup is now noise-only for no-format arithmetic. The no-rounding branch of removeFloatingPointErrors cleans binary noise (0.1 + 0.2 → 0.3) via toPrecision(15), but only when the correction is within a capped epsilon (min(Number.EPSILON * max(1, |value|), 1e-10)). The cap stops toPrecision(15) from corrupting large fractional values and high-significance step values — e.g. 100000000000000.1 + 0.1, 0.1234567890123456, and Number.MAX_SAFE_INTEGER are returned verbatim because their delta exceeds the cap.
  • Parsed input (typing, paste, blur) carries no arithmetic noise, so toValidatedNumber returns it verbatim when there is no step and no rounding format — keeping every typed digit, including values beyond 15 significant digits.
  • This fixes step / smallStep finer than 0.001 at the numeric value level: the value now advances and onValueChange fires, even though the visible text still rounds per Intl defaults.

Interactions read numeric state, not rounded display

  • Button increment/decrement: useNumberFieldButton's commitValue now parses inputValue before stepping only when the input is dirty and uncommitted (!allowInputSyncRef.current). When the input is already synced, it steps from the numeric state instead of the rounded visible text.
  • Keyboard ArrowUp/ArrowDown: same authority rule — parse inputValue only when the input has unsaved edits; otherwise step from the numeric state (valueRef). Previously the keyboard path always parsed the rounded display, so a synced field collapsed precision (e.g. 1.23456 → 2.235 instead of 2.23456). Wheel and scrub already stepped from numeric state.
  • Input blur: when the input wasn't manually edited and there are no rounding options, blur commits the stored numeric value as-is instead of re-parsing the rounded display text. A no-edit focus/blur, or a blur after a programmatic change, no longer discards precision. (With explicit rounding options, blur still rounds the committed value to the format.)

Display formatting unchanged (compatibility-preserving)

  • The blur handler and controlled-value sync always format visible text with the default formatNumber path (the max-precision display path is removed). Visible text follows Intl.NumberFormat defaults exactly as before — no full-precision display by default.
  • Explicit Intl rounding options from [number field] Respect Intl rounding options on blur #4804 (roundingMode, significant digits, roundingIncrement, percent display-scale rounding on blur) are still respected; that branch is unchanged.

Behavior (no format, value 1.23456)

Action Displayed text Numeric value (onValueChange / onValueCommitted)
type 1.23456, then blur 1.235 (Intl default) 1.23456
re-focus + blur with no edit 1.235 (unchanged) 1.23456 (unchanged, no commit)
increment +1 (button or ArrowUp) 2.235 (Intl default) 2.23456
step={0.0001} from 0 0 (Intl default) advances 0.0001, 0.0002, … (was a silent no-op)

Visible text matches the pre-regression default formatting; only the numeric value pipeline is corrected so precision is no longer lost.

Tests

  • Reframed the tests that asserted the accidental 3-digit numeric default or the max-precision display: they now assert default-formatted display text alongside full-precision numeric values.
  • Added regression tests:
    • stepping from numeric state rather than rounded display text — buttons (uncontrolled defaultValue, and after typed precision is formatted on blur) and keyboard ArrowUp (synced defaultValue, and after a no-edit blur cycle);
    • a no-edit focus/blur cycle keeping full numeric precision, including subsequent stepping;
    • a canceled synced button step not committing a stale value after an external change;
    • sub-0.001 step / smallStep advancing the numeric value and firing onValueChange;
    • removeFloatingPointErrors unit tests for noise cleanup (incl. negative), the capped epsilon (large fractional, high-significance step, safe-integer exactness), and verbatim parsed input beyond 15 significant digits.

The stored value was rounded to 3 fraction digits when no Intl rounding
options were provided, an accidental default inherited from
Intl.NumberFormat's resolved maximumFractionDigits. This truncated
committed values (a regression from v1.5.0, which committed full
precision on blur) and made step/smallStep values finer than 0.001
silent no-ops.

Clean only binary floating-point noise in the default branch instead,
preserving legitimate precision. The Intl round-trip branch for explicit
rounding options is unchanged.
@atomiks atomiks added component: number field Changes related to the number field component. type: bug It doesn't behave as expected. labels Jun 12, 2026
@pkg-pr-new

pkg-pr-new Bot commented Jun 12, 2026 •

Copy link
Copy Markdown

commit: c61f408

@code-infra-dashboard

code-infra-dashboard Bot commented Jun 12, 2026 •

Copy link
Copy Markdown

Bundle size

Bundle Parsed size Gzip size
@base-ui/react 🔺+27B(+0.01%) 🔺+31B(+0.02%)

Details of bundle changes

Performance

Total duration: 1,335.05 ms +24.46 ms(+1.9%) | Renders: 50 (+0) | Paint: 2,038.16 ms +27.48 ms(+1.4%)

No significant changes — details


Check out the code infra dashboard for more information about this PR.

@atomiks atomiks added type: regression A bug, but worse, it used to behave as expected. internal Behind-the-scenes enhancement. Formerly called “core”. and removed type: bug It doesn't behave as expected. labels Jun 12, 2026
@netlify

netlify Bot commented Jun 12, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for base-ui ready!

Name Link
🔨 Latest commit c61f408
🔍 Latest deploy log https://app.netlify.com/projects/base-ui/deploys/6a2fa79306218f00087d3692
😎 Deploy Preview https://deploy-preview-5040--base-ui.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

Values typed with more than 15 significant digits were rounded by the
toPrecision(15) noise cleanup, so a no-format field could report and
commit a different value than the user entered.

Parsed input (typing, paste, blur) involves no arithmetic — percent and
permille scaling shift the decimal exponent as a string — so it carries
no binary noise and is now returned verbatim. Cleanup still applies to
stepping and snapping, whose arithmetic can introduce noise; a flat cap
preserving 16 digits could not clean 16-digit noise patterns such as
0.1 + 0.7 === 0.7999999999999999.
@atomiks
atomiks marked this pull request as ready for review June 15, 2026 00:24

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

This PR adjusts NumberField validation/rounding so the stored/committed numeric value preserves full precision by default, while still cleaning only true binary floating-point noise and continuing to respect explicit Intl rounding options.

Changes:

  • Replace the previous default 3-fraction-digit rounding with a tolerance-based “binary noise cleanup” approach (toPrecision(15) + delta thresholding) when no Intl rounding options are provided.
  • Skip floating-point cleanup entirely for parsed input paths (typing/paste/blur) when there’s no stepping and no Intl rounding options, preserving all typed digits that round-trip through number.
  • Update and add tests covering sub-0.001 step/smallStep behavior, blur commit precision, and utility-level cleanup/precision edge cases.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
packages/react/src/number-field/utils/validate.ts Updates floating-point cleanup and validation flow to preserve full precision by default and only clean arithmetic noise.
packages/react/src/number-field/utils/validate.test.ts Adds/updates unit tests for precision preservation, noise cleanup, and stepping vs parsed-input behavior.
packages/react/src/number-field/input/NumberFieldInput.test.tsx Updates blur precision expectations and adds regression coverage for high-precision typing and fine-grained smallStep.
packages/react/src/number-field/increment/NumberFieldIncrement.test.tsx Updates increment expectations to reflect preserved precision and adds step-finer-than-0.001 regression coverage.
packages/react/src/number-field/decrement/NumberFieldDecrement.test.tsx Updates decrement expectation to reflect preserved precision after stepping.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@atomiks
atomiks requested a review from Copilot June 15, 2026 03:15
@atomiks atomiks changed the title [number field] Preserve full numeric precision by default [number field] Preserve numeric precision while keeping default display formatting Jun 15, 2026

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 8 out of 8 changed files in this pull request and generated 2 comments.

atomiks added 2 commits June 15, 2026 13:40
A focus/blur with no edits (or a blur after a programmatic change) re-parsed
the rounded display text and overwrote the stored value, discarding precision.
Commit the authoritative numeric value as-is when the input wasn't manually
edited and there are no Intl rounding options; explicit rounding options still
apply. Also reword an inaccurate test comment about double round-tripping.
The synced early-return in commitValue skipped the setValue that used to
refresh lastChangedValueRef, so a canceled step after an earlier change could
fire onValueCommitted with a stale value. Refresh the ref to the current value
on the synced path. Also drop the now-unused formatNumberMaxPrecision helper.
atomiks added 4 commits June 15, 2026 15:23
Keyboard ArrowUp/ArrowDown always parsed the visible (rounded) input text and
passed it as currentValue, so a synced field stepped from the display string
and collapsed precision (e.g. defaultValue 1.23456 shown as 1.235 stepped to
2.235 instead of 2.23456). Apply the same dirty/synced authority rule as the
button path: parse inputValue only when the input has unsaved edits, otherwise
let incrementValue step from valueRef.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 9 out of 9 changed files in this pull request and generated 1 comment.

@flaviendelangle flaviendelangle left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

PR #5040 Review — [number field] Preserve numeric precision while keeping default display formatting

Author: atomiks · +623 / −97 · 9 files (4 source, 4 test, 1 util) · branch fetched locally as pr-5040-review

The core fix is correct and well-motivated: removeFloatingPointErrors no longer rounds the stored numeric value to an accidental 3-digit default, the step/keyboard/blur paths now read the authoritative numeric state instead of the rounded display, and the cancel/stale-commit guards check out. Tests assert both the numeric value and the display. No CLAUDE.md/AGENTS.md violations, no dead code, clean removal of formatNumberMaxPrecision/getControlledInputValue. The findings below are about edges and one regression.

Verification note: agents couldn't run the Vitest suite (no node_modules in the worktree; the working tree has unrelated combobox changes). I verified the FP math in Node and traced control flow against master directly.


🔴 Critical (1)

C1 — Typed value silently discarded on blur after a cursor key (regression, non-mirroring controlled value)

packages/react/src/number-field/input/NumberFieldInput.tsx:181-194 (new committed = value branch)

The new blur branch if (!hadManualInput && !hasRoundingOptions) committed = value; trusts the numeric value over the visible text. But any key in NAVIGATE_KEYS (ArrowLeft, ArrowRight, Home, End, Tab, Backspace, Delete) resets allowInputSyncRef.current = true at the top of onKeyDown and returns early — so a dirty input becomes hadManualInput === false on the next blur.

Verified trace (controlled field whose parent does not mirror onValueChange back into value, e.g. lagging/async/validated state):

  1. Type 5 → onValueChange(5) fires, parent keeps value = 0, display shows "5", allowInputSyncRef = false.
  2. Press ArrowLeft (move cursor) → allowInputSyncRef = true, early return. Display still "5".
  3. Blur → hadManualInput = false → committed = value = 0 → shouldUpdateValue = (0 !== 0) = false → setValue never called, no onValueChange; display reverts to "0". The typed 5 is silently lost.

In master, blur set committed = parsedValue (5), so the value survived. This is a regression, reachable through the ordinary "type → arrow → click away" interaction — and the lagging-controlled pattern is one this very PR endorses with its new test steps keyboard from dirty input text when the controlled value lags onValueChange.

Note: the code-reviewer agent argued this branch was safe ("matches master because parsedValue === value"); that assumption doesn't hold here (parsedValue 5 !== value 0), which is why the deeper data-flow pass caught it.

Fix direction: only short-circuit to value when the text genuinely is the formatted form of value (e.g. fall back to parsedValue when parsedValue !== value), and add a "type → ArrowLeft → blur" regression test on a non-mirroring controlled field. (Precondition is non-mirroring controlled; if the team considers that out of scope, downgrade — but it's silent data loss in a documented-supported pattern.)


🟠 Important (3)

I1 — removeFloatingPointErrors comment example is factually wrong + threshold imprecise

packages/react/src/number-field/utils/validate.ts:45-47

Verified in Node: 1000000.1 + 0.1 === 1000000.2 exactly (cleanupDelta = 0) — it is returned already-clean, so it does not demonstrate "noise left uncleaned." A genuinely-uncleaned example is 1000000.1 + 0.2 → 1000000.2999999999. Also, the "above ~1e6" threshold is ~2× too high: a single ULP first exceeds the 1e-10 cap at the 2^19 ≈ 5.2e5 binade (524288.3 + 0.3 is left uncleaned; 524287.6 is still clean). Suggest: fix the example to 1000000.1 + 0.2 and state "~5e5 (the 2^19 binade)".

I2 — Large-magnitude binary noise leaks into onValueChange/onValueCommitted/form value

packages/react/src/number-field/utils/validate.ts:51

The documented tradeoff isn't contained to internal math: above ~5.2e5 the raw noisy value flows to the change/commit callbacks and the hidden form input, while the default-formatted display (maximumFractionDigits: 3) hides it. Verified: stepping 1000000 by 0.1 thrice yields 1000000.2999999999 to consumers while the UI shows 1,000,000.3. Consider a magnitude-relative tolerance (compare significant digits rather than an absolute 1e-10 cap) so cleanup is consistent across magnitudes, or document the limit in public docs (not just a code comment) since it changes the numeric contract for large values.

I3 — Asymmetric test coverage: decrement / ArrowDown from synced numeric state

NumberFieldDecrement.test.tsx, NumberFieldInput.test.tsx

The keyboard handler merged ArrowUp/ArrowDown into one branch and useNumberFieldButton rewrote both directions, but the new precision tests are almost all ArrowUp / increment. There's no test that ArrowDown advances the full-precision numeric value (1.23456 → 0.23456, not 0.235), and the decrement button got none of the four precision tests its increment sibling did. A sign/direction-specific regression would pass the entire added suite (only the cancel case is covered symmetrically). Also: the >5e5 "noise left uncleaned" tradeoff is asserted only in a comment — add a unit test pinning removeFloatingPointErrors(1000000.1 + 0.2) returns the raw sum.


🟡 Suggestions (4)

  • S1 — Dedup the step+commit sequence into a context helper. NumberFieldInput.tsx:385-405 and useNumberFieldButton.ts:55-65,114-133 repeat "refresh lastChangedValueRef on synced path → snapshot prev → incrementValue → commit if committed !== prev." AGENTS.md prefers sharing via the parent/context. A stepValue(amount, {direction, currentValue, refreshCommitRef, ...}) on the root context collapses both. Keep commitValue/currentValue derivation and the Home/End unconditional-commit path outside it. (Verify against the cancel-after-external-change tests — commit-ref timing is delicate.)
  • S2 — -0 flattened to +0. validate.ts:43 parseFloat((-0).toPrecision(15)) returns +0; Number.isFinite(-0) doesn't guard it. Low reachability (the new early-return skips cleanup for parsed input), but a one-line if (Object.is(value, -0)) return value; is cheap correctness.
  • S3 — toValidatedNumber early return is broader than its comment. validate.ts:131-137: the guard is purely "not stepping," so externally-supplied noisy controlled values (value={0.1+0.2}) are also returned verbatim, and the Number.isFinite guard is now path-dependent (only removeFloatingPointErrors enforces it). Broaden the comment to "non-stepping values (typed/pasted/blurred, and external)"; confirm parseNumber can't yield non-finite on the clamp:false path.
  • S4 — Clarity nits. Reorder the blur committed if/else to lead with the dominant hasRoundingOptions axis (NumberFieldInput.tsx:181-194); add a one-liner noting MAX_FLOATING_POINT_CLEANUP_DELTA is an absolute cap vs the coincidentally-equal relative STEP_EPSILON_FACTOR (validate.ts:5-6) so a future reader doesn't merge them.

✅ Strengths

  • Root cause correctly identified (the ?? 20 that never applied because Intl's resolved default is 3); fix preserves display compatibility while restoring numeric precision.
  • Cancel/stale-commit guards verified correct on the synced path: setValue returns before writing lastChangedValueRef on cancel, so the refreshed ref equals prev and no stale commit fires — and this is tested across all three entry points.
  • Tests assert numeric truth (onValueChange/onValueCommitted) and display (toHaveValue), not refs. No flushMicrotasks-after-render or JSDOM-layout violations.
  • Clean removal of formatNumberMaxPrecision/getControlledInputValue with no dangling references; imports correctly pruned.
  • Excellent "why" comments with cross-path invariant references (the one factual slip is I1).

Recommended action

  1. Resolve C1 (or consciously scope it out) — the only behavior regression; add the type→arrow→blur test.
  2. Fix the I1 comment (wrong example + threshold) — quick and verifiably incorrect today.
  3. Decide on I2 — relative tolerance vs. public-docs the large-value limit.
  4. Close I3 test gaps — symmetric ArrowDown/decrement precision tests + the >5e5 unit test.
  5. Suggestions S1–S4 at the author's discretion.

@atomiks

atomiks commented Jun 15, 2026

Copy link
Copy Markdown
Contributor Author
  • C1 is already fixed (the top-of-onKeyDown reset is gone as of f39fd5e). Worth noting: its suggested fix-direction ("fall back to parsedValue when parsedValue !== value") would actually re-break the core case — for a genuinely synced field, parsedValue is the rounded display (1.235) and value is full precision (1.23456), so falling back to parsedValue would reintroduce the precision collapse. The real fix was the dirty-flag ordering. I'll add the exact type → ArrowLeft → blur test to lock it in.

Fixed the others.

@atomiks
atomiks merged commit 4e97595 into mui:master Jun 15, 2026
6 checks passed
@atomiks
atomiks deleted the claude/heuristic-ramanujan-976212 branch June 15, 2026 07:25
@michaldudak michaldudak mentioned this pull request Jun 17, 2026
@michaldudak michaldudak removed the internal Behind-the-scenes enhancement. Formerly called “core”. label Jun 17, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

component: number field Changes related to the number field component. type: regression A bug, but worse, it used to behave as expected.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants