# NumberField

> A locale-aware numeric spin button from @salmonui/inputs/number-field, with Intl and Data Grid formats, stepping, clamping and form submission.

Canonical: https://salmonui.dev/docs/inputs/number-field

`NumberField` is a numeric input. It is a native text input
with `role="spinbutton"` (`inputmode="decimal"`), formatted when blurred and
raw while focused; a hidden input with `name` submits the number.

```tsx
import { NumberField } from '@salmonui/inputs/number-field';
import '@salmonui/inputs/number-field/styles.css';

<NumberField name="price" label="Price" locale="de-DE" currency="EUR" min={0} step={0.5} />
```

### Live demo: NumberField basics

Live demo: https://salmonui.dev/demos/inputs/number-field-basics

A controlled quantity with a range and steppers, a German currency field and a percent preset.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { NumberField } from '@salmonui/inputs/number-field';

// A controlled quantity with a range, a German currency field and a percent preset.
export default function NumberFieldBasicsDemo() {
  const [qty, setQty] = useState<number | null>(3);
  return (
    <div style={{ display: 'grid', gap: 16, maxWidth: 320 }}>
      <NumberField label="Quantity" value={qty} onValueChange={setQty} min={0} max={20} description="0 to 20; Page keys step by 10" />
      <output>Value: {String(qty)}</output>
      <NumberField label="Preis" locale="de-DE" currency="EUR" defaultValue={1234.5} step={0.5} />
      <NumberField label="Discount" format="P1" defaultValue={0.125} step={0.005} />
    </div>
  );
}
```

## Value and format

- Controlled with `value` and `onValueChange`, uncontrolled with
  `defaultValue` (a form reset restores it); an empty field is `null`.
- `value: number | null` / `defaultValue` / `onValueChange(value, details)`
  with `details.formattedValue` and
  `reason` (`'input' | 'increment' | 'decrement' | 'clamp' | 'clear' |
  'reset'`).
- `formatOptions` (`Intl.NumberFormatOptions`) or `format` with the Data
  Grid `column.format` presets and patterns (`'N2'`, `'C2'`, `'P1'`,
  `'#,##0.00'`), one formatter for both. `currency` sets the ISO
  4217 code.
- `locale` drives formatting and parsing (default `'en-US'`; the browser
  locale is never read, so server and client markup agree). Typed text is
  parsed with `parseNumber` from `@salmonui/data-grid/engine/locale`: group,
  decimal, minus, currency and percent symbols of the locale.
- `decimals` rounds the committed value; `restrictDecimals` refuses typing
  more fraction digits.

### Live demo: Number precision and clamping

Live demo: https://salmonui.dev/demos/inputs/number-field-precision

NumberField decimals rounding the committed value, restrictDecimals refusing extra fraction digits while typing, clampBehavior blur or none, and details.formattedValue as the displayed text.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { NumberField } from '@salmonui/inputs/number-field';
import { Select } from '@salmonui/dropdowns/select';

// Precision and range handling: `decimals` rounds the committed value,
// `restrictDecimals` refuses extra fraction digits while typing,
// `clampBehavior` clamps on blur or keeps the value and reports the error,
// and `details.formattedValue` is the text the blurred field shows.
export default function NumberFieldPrecisionDemo() {
  const [restrict, setRestrict] = useState(false);
  const [clamp, setClamp] = useState<'blur' | 'none'>('blur');
  const [weight, setWeight] = useState<number | null>(2.5);
  const [weightText, setWeightText] = useState('2.50 kg');
  const [reason, setReason] = useState('none');
  const [age, setAge] = useState<number | null>(30);
  return (
    <>
      <div className="demo-toolbar">
        <Checkbox checked={restrict} onCheckedChange={(checked) => setRestrict(checked)}>
          restrictDecimals
        </Checkbox>
        <label>
          clampBehavior
          <Select aria-label="clampBehavior" data={['blur', 'none']} value={clamp} onValueChange={(value) => value != null && setClamp(value as 'blur' | 'none')} />
        </label>
      </div>
      <div style={{ display: 'grid', gap: 16, justifyItems: 'start' }}>
        <NumberField
          label="Weight"
          style={{ inlineSize: 340, maxInlineSize: '100%' }}
          decimals={2}
          restrictDecimals={restrict}
          step={0.25}
          formatOptions={{ style: 'unit', unit: 'kilogram', minimumFractionDigits: 2, maximumFractionDigits: 2 }}
          value={weight}
          onValueChange={(value, details) => {
            setWeight(value);
            setWeightText(details.formattedValue);
            setReason(details.reason);
          }}
          description="decimals={2}: type 1.23456 and blur"
        />
        <output>
          value {String(weight)} · details.formattedValue {JSON.stringify(weightText)} · reason {reason}
        </output>
        <NumberField label="Age" style={{ inlineSize: 340, maxInlineSize: '100%' }}min={18} max={99} clampBehavior={clamp} value={age} onValueChange={setAge} description="18 to 99: type 150 and blur" />
        <output>Age value: {String(age)}</output>
      </div>
    </>
  );
}
```

## Range and stepping

- `min`, `max`, `step` (default 1). Float steps keep the
  step's precision (0.1 + 0.2 is 0.3).
- `clampBehavior: 'blur'` (default) clamps on blur; `'none'` keeps the value
  and reports the range error through the field (`aria-invalid`, the
  `validationMin` / `validationMax` messages).
- `showStepper` (default true) shows increment and decrement buttons that
  repeat while held; they are not tab stops.
- `incrementOnWheel` lets the wheel step a focused field. It is off by
  default because scrolling a page over a focused field should not change
  data (see [Design notes](https://salmonui.dev/docs/inputs/number-field#design-notes)).

## Keyboard

| Key | Action |
| --- | --- |
| ArrowUp / ArrowDown | Step by `step` |
| PageUp / PageDown | Step by ten steps |
| Home / End | Go to `min` / `max` (when set) |
| Escape | Clears a `clearable` field |

Screen readers hear a spin button with `aria-valuenow`, `aria-valuemin`,
`aria-valuemax` and the formatted `aria-valuetext`.

## Performance

A keystroke costs well under 0.5 ms of component work for NumberField and
MaskedField (`tests/browser/inputs-structured.spec.ts`); only the
edited field re-renders.

## SSR

Server and client render the same text because the format uses `locale`
(default `'en-US'`), never the browser locale. Before hydration the field
is a labelled text input showing the formatted value, and the hidden named
input submits the number.

## Design notes

- the mouse wheel does not change the value by default, so
  scrolling the page over a focused field never edits it. Pass
  `incrementOnWheel` to step the value with the wheel.
- there are no step methods; methods on a component instance do
  not fit React's data flow; `ref` is the native input. Step a controlled
  value instead: `setValue((v) => (v ?? 0) + 5)`.

## API

| Prop | Type | Default |
| --- | --- | --- |
| `value`, `defaultValue` | `number \| null` | `null` |
| `onValueChange` | `(value, { formattedValue, source, reason }) => void` | |
| `min`, `max`, `step` | `number` | step `1` |
| `formatOptions` | `Intl.NumberFormatOptions` | |
| `format`, `currency`, `locale` | `string` | locale `'en-US'` |
| `decimals`, `restrictDecimals` | `number`, `boolean` | |
| `clampBehavior` | `'blur' \| 'none'` | `'blur'` |
| `showStepper`, `incrementOnWheel` | `boolean` | `true`, `false` |
| `localeText` | `{ increment, decrement, clear, validation* }` | English |
| shared field props | `label`, `description`, `errorMessage`, `invalid`, `validation`, `validateOn`, `size`, `clearable`, adornments | |

`ref` is the visible native `<input>`; unknown props go to it. Full
signatures: [`@salmonui/inputs/number-field` API reference](https://salmonui.dev/docs/reference/inputs/number-field).
