Repository navigation
[number field] Preserve numeric precision while keeping default display formatting - #5040
Conversation
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.
commit: |
Bundle size
PerformanceTotal 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. |
✅ Deploy Preview for base-ui ready!
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.
There was a problem hiding this comment.
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.001step/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.
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.
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.
flaviendelangle
left a comment
There was a problem hiding this comment.
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_modulesin the worktree; the working tree has unrelated combobox changes). I verified the FP math in Node and traced control flow againstmasterdirectly.
🔴 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):
- Type
5→onValueChange(5)fires, parent keepsvalue = 0, display shows"5",allowInputSyncRef = false. - Press ArrowLeft (move cursor) →
allowInputSyncRef = true, early return. Display still"5". - Blur →
hadManualInput = false→committed = value = 0→shouldUpdateValue = (0 !== 0) = false→setValuenever called, noonValueChange; display reverts to"0". The typed5is 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-405anduseNumberFieldButton.ts:55-65,114-133repeat "refreshlastChangedValueRefon synced path → snapshotprev→incrementValue→ commit ifcommitted !== prev." AGENTS.md prefers sharing via the parent/context. AstepValue(amount, {direction, currentValue, refreshCommitRef, ...})on the root context collapses both. KeepcommitValue/currentValuederivation and theHome/Endunconditional-commit path outside it. (Verify against the cancel-after-external-change tests — commit-ref timing is delicate.) - S2 —
-0flattened to+0.validate.ts:43parseFloat((-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-lineif (Object.is(value, -0)) return value;is cheap correctness. - S3 —
toValidatedNumberearly 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 theNumber.isFiniteguard is now path-dependent (onlyremoveFloatingPointErrorsenforces it). Broaden the comment to "non-stepping values (typed/pasted/blurred, and external)"; confirmparseNumbercan't yield non-finite on theclamp:falsepath. - S4 — Clarity nits. Reorder the blur
committedif/else to lead with the dominanthasRoundingOptionsaxis (NumberFieldInput.tsx:181-194); add a one-liner notingMAX_FLOATING_POINT_CLEANUP_DELTAis an absolute cap vs the coincidentally-equal relativeSTEP_EPSILON_FACTOR(validate.ts:5-6) so a future reader doesn't merge them.
✅ Strengths
- Root cause correctly identified (the
?? 20that never applied because Intl's resolved default is3); fix preserves display compatibility while restoring numeric precision. - Cancel/stale-commit guards verified correct on the synced path:
setValuereturns before writinglastChangedValueRefon cancel, so the refreshed ref equalsprevand no stale commit fires — and this is tested across all three entry points. - Tests assert numeric truth (
onValueChange/onValueCommitted) and display (toHaveValue), not refs. NoflushMicrotasks-after-render or JSDOM-layout violations. - Clean removal of
formatNumberMaxPrecision/getControlledInputValuewith no dangling references; imports correctly pruned. - Excellent "why" comments with cross-path invariant references (the one factual slip is I1).
Recommended action
- Resolve C1 (or consciously scope it out) — the only behavior regression; add the type→arrow→blur test.
- Fix the I1 comment (wrong example + threshold) — quick and verifiably incorrect today.
- Decide on I2 — relative tolerance vs. public-docs the large-value limit.
- Close I3 test gaps — symmetric ArrowDown/decrement precision tests + the >5e5 unit test.
- Suggestions S1–S4 at the author's discretion.
Fixed the others. |
…x cleanup comments
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.NumberFormatdefaults (e.g.1.235for a no-format field), while the stored numeric value no longer loses precision when stepping or on blur.What was wrong
removeFloatingPointErrorsrounded the stored numeric value to 3 fraction digits wheneverformathad no Intl rounding options. The 3-digit default was accidental: the original code intended a full-precision fallback (... ?? defaultOptions.maximumFractionDigits ?? 20), butnew Intl.NumberFormat().resolvedOptions().maximumFractionDigitsis3, so the?? 20never applied.Consequences:
step/smallStepfiner than0.001were silent no-ops at the numeric level: incrementing from0by0.0001rounded back to0, soonValueChangenever fired and the value never advanced. Native<input type="number" step="0.0001">works fine.1.23456— displayed as1.235— advanced from the rounded1.235, dropping precision even when the input wasn't dirty.What changed
Numeric pipeline keeps precision (display unchanged)
removeFloatingPointErrorscleans binary noise (0.1 + 0.2→0.3) viatoPrecision(15), but only when the correction is within a capped epsilon (min(Number.EPSILON * max(1, |value|), 1e-10)). The cap stopstoPrecision(15)from corrupting large fractional values and high-significance step values — e.g.100000000000000.1 + 0.1,0.1234567890123456, andNumber.MAX_SAFE_INTEGERare returned verbatim because their delta exceeds the cap.toValidatedNumberreturns it verbatim when there is no step and no rounding format — keeping every typed digit, including values beyond 15 significant digits.step/smallStepfiner than0.001at the numeric value level: the value now advances andonValueChangefires, even though the visible text still rounds per Intl defaults.Interactions read numeric state, not rounded display
useNumberFieldButton'scommitValuenow parsesinputValuebefore 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.ArrowUp/ArrowDown: same authority rule — parseinputValueonly 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.235instead of2.23456). Wheel and scrub already stepped from numeric state.Display formatting unchanged (compatibility-preserving)
formatNumberpath (the max-precision display path is removed). Visible text followsIntl.NumberFormatdefaults exactly as before — no full-precision display by default.roundingMode, significant digits,roundingIncrement, percent display-scale rounding on blur) are still respected; that branch is unchanged.Behavior (no
format, value1.23456)onValueChange/onValueCommitted)1.23456, then blur1.235(Intl default)1.234561.235(unchanged)1.23456(unchanged, no commit)+1(button orArrowUp)2.235(Intl default)2.23456step={0.0001}from00(Intl default)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
defaultValue, and after typed precision is formatted on blur) and keyboardArrowUp(synceddefaultValue, and after a no-edit blur cycle);0.001step/smallStepadvancing the numeric value and firingonValueChange;removeFloatingPointErrorsunit 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.