Skip to content

[number field] Fix format rounding error on blur - #4557

Merged
atomiks merged 1 commit into
mui:masterfrom
atomiks:codex/issue-4554-number-field-format
Apr 8, 2026
Merged

atomiks merged 1 commit into
mui:masterfrom
atomiks:codex/issue-4554-number-field-format

Conversation

@atomiks

@atomiks atomiks commented Apr 8, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #4554

On blur, NumberField was always doing an extra max-precision formatting pass to decide whether to preserve a user's typed precision. That helper forces maximumFractionDigits: 20, which makes valid roundingIncrement formats invalid when they already use fixed fraction digits.

Changes

  • Only run the max-precision preservation check when the field does not have explicit fraction precision.
  • Keep the existing blur behavior for unconstrained values.
  • Add a regression test for roundingIncrement with fixed fraction digits on blur.

@atomiks atomiks added type: bug It doesn't behave as expected. component: number field Changes related to the number field component. labels Apr 8, 2026 — with ChatGPT Codex Connector
@pkg-pr-new

pkg-pr-new Bot commented Apr 8, 2026

Copy link
Copy Markdown
  • base-ui-tanstack-start

  • vite-css-base-ui-example

    pnpm add https://pkg.pr.new/mui/base-ui/@base-ui/react@4557
    
    pnpm add https://pkg.pr.new/mui/base-ui/@base-ui/utils@4557
    

commit: 6636c75

@mui-bot

mui-bot commented Apr 8, 2026 •

Copy link
Copy Markdown

Bundle size report

Bundle Parsed size Gzip size
@base-ui/react ▼-4B(0.00%) ▼-3B(0.00%)

Details of bundle changes


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

@atomiks atomiks changed the title [number-field] Fix blur format rounding error [number field] Fix format rounding error on blur Apr 8, 2026
@netlify

netlify Bot commented Apr 8, 2026

Copy link
Copy Markdown

✅ Deploy Preview for base-ui ready!

Name Link
🔨 Latest commit 6636c75
🔍 Latest deploy log https://app.netlify.com/projects/base-ui/deploys/69d5fa78816ecb00084678d7
😎 Deploy Preview https://deploy-preview-4557--base-ui.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

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

@atomiks
atomiks marked this pull request as ready for review April 8, 2026 06:54

@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 Review: #4557 — [number field] Fix format rounding error on blur

PR: #4557
Author: atomiks
Files changed: 2 (3 additions, 2 deletions in source; 26 additions in tests)


Summary

The PR fixes a bug where NumberField's blur handler unconditionally called formatNumberMaxPrecision(), which overrides maximumFractionDigits to 20. This conflicts with roundingIncrement format options that require specific maximumFractionDigits values, causing Intl.NumberFormat to throw a RangeError.

The fix leverages JavaScript short-circuit evaluation to skip the formatNumberMaxPrecision() call when explicit fraction precision is already configured.


Critical Issues (0 found)

None.


Important Issues (2 found)

1. Missing explanatory comment — NumberFieldInput.tsx:215-218

The short-circuit on !hasExplicitPrecision is not just an optimization — it prevents a crash. formatNumberMaxPrecision overrides maximumFractionDigits: 20, which is incompatible with roundingIncrement. A future developer could refactor the && chain back to a variable assignment for "readability" and reintroduce the bug.

Recommendation: Add a brief comment explaining why the short-circuit is load-bearing:

// formatNumberMaxPrecision overrides maximumFractionDigits to 20, which is
// incompatible with roundingIncrement and other precision-constrained options.
// Only call it when the format has no explicit fraction precision.
const shouldPreserveFullPrecision =
  !hasExplicitPrecision &&
  parsedValue === value &&
  inputValue === formatNumberMaxPrecision(parsedValue, locale, formatOptions);

2. formatNumberMaxPrecision is inherently fragile — formatNumber.ts:28-37

The function blindly overrides maximumFractionDigits: 20 regardless of other conflicting options. Every caller must independently guard against the crash. A safer long-term approach would be for the function itself to avoid the override when roundingIncrement is set:

export function formatNumberMaxPrecision(
  value: number | null,
  locale?: Intl.LocalesArgument,
  options?: Intl.NumberFormatOptions,
) {
  const maxFrac = options?.roundingIncrement != null
    ? options.maximumFractionDigits
    : 20;
  return formatNumber(value, locale, { ...options, maximumFractionDigits: maxFrac });
}

This is not blocking for this PR but worth considering as a follow-up.


Suggestions (3 found)

1. Add a type-then-blur test — NumberFieldInput.test.tsx

The current test only does programmatic focus() / blur() on a pre-set defaultValue. The most realistic user scenario — typing a value and then blurring — is not tested. This is the actual workflow that would trigger the error in production.

it('should format correctly on blur after typing when format uses roundingIncrement', async () => {
  const format = {
    minimumFractionDigits: 1,
    maximumFractionDigits: 1,
    roundingIncrement: 5,
  };
  const { user } = await render(
    <NumberField.Root format={format}>
      <NumberField.Input />
    </NumberField.Root>,
  );
  const input = screen.getByRole('textbox');
  await act(async () => input.focus());
  await user.keyboard('1.3');
  fireEvent.blur(input);
  const expected = new Intl.NumberFormat(undefined, format).format(1.5);
  expect(input).toHaveValue(expected);
});

2. Add a controlled-value test — NumberFieldInput.test.tsx

The second call site for formatNumberMaxPrecision is in getControlledInputValue (NumberFieldRoot.tsx:700). While it's already guarded by the same explicitPrecision check, a controlled-value test with roundingIncrement would protect against future regressions in that code path.

3. Test with a different roundingIncrement value

Only roundingIncrement: 5 with maximumFractionDigits: 1 is tested. Testing at least one more combination (e.g., roundingIncrement: 25 with maximumFractionDigits: 2) would add confidence, though the root cause is the same.


Strengths

  • Correct and minimal fix. The change is 3 lines of source, directly addressing the root cause without over-engineering.
  • Good use of short-circuit evaluation. The fix is a minor performance improvement too — formatNumberMaxPrecision is no longer called when its result would be unused.
  • Solid regression test. Uses Intl.NumberFormat to compute the expected value dynamically, making the test locale-independent.
  • Consistent with existing patterns. The fix aligns NumberFieldInput.tsx's blur handler with the already-correct guard in getControlledInputValue (NumberFieldRoot.tsx:696-700).
  • Commit message follows the [scope] Imperative summary convention.

Recommended Action

  1. Consider adding an explanatory comment at the call site (Important Issue #1) — low effort, high value.
  2. Optionally add a type-then-blur test (Suggestion #1) to cover the realistic user scenario.
  3. Merge — the fix is correct and solves the reported bug. The fragility of formatNumberMaxPrecision (Important Issue #2) can be addressed in a follow-up.

@atomiks
atomiks merged commit 70ad7e8 into mui:master Apr 8, 2026
7 of 8 checks passed
@atomiks
atomiks deleted the codex/issue-4554-number-field-format branch April 8, 2026 07:30
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: bug It doesn't behave as expected.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[number field] Valid format prop throws error

3 participants