Skip to content
Browse documentation

A locale-aware money field with caret-safe typing, currency formatting, keyboard steps and clean numeric values for your backend.

Used forPricing and plansInvoicesCommerce settingsFinance forms

Install with the shadcn CLI

$ npx shadcn@latest add https://hairlineui.com/r/currency-input.json

Registered the namespace? Then it’s shadcn add @hairline/currency-input. Set it up

Templates

Need the whole page?

61 Next.js landing pages, each designed from scratch. Try any of them live; one is $39, all of them $159, and 6 are free.

All 61 templates

Where it’s used

  • Pricing and plans

    Enter a monthly or annual price with live totals.

  • Invoices

    Type line-item amounts in the customer’s currency and locale.

  • Commerce settings

    Set product prices, discounts and shipping thresholds.

  • Finance forms

    Collect budgets, expenses and transfer amounts as clean numbers.

What it handles for you

Currency editing needs locale separators, stable caret behaviour, currency precision and numeric output. Formatting alone does not solve those; the editing state has to be separate from the stored value.

Instead of wiring upnative <input type="number">react-number-formatmanual Intl.NumberFormat wiringlocale separator parsingcurrency fraction-digit helpers
  1. Grouping as you type

    Separators appear while you type and the caret stays after the same digit, in any locale’s grouping and decimal mark.

  2. Locale and currency

    Intl supplies grouping, decimal separators, symbol position and the currency’s own fraction digits.

  3. Numeric integration

    Callbacks and hidden form values carry number or null, never currency symbols or grouped text.

  4. Validation with recovery

    Unreadable and out-of-range drafts stay in the field with a precise error; Escape restores the settled value.

  5. Keyboard stepping

    Arrow Up and Down move by step (Shift for ten steps) with decimal-safe rounding and a small bump at the limit.

  6. Responsive field states

    Currency symbols morph when the currency changes, Clear folds its own width open, and errors replace the hint.

Overview

Money fields often reformat on every keystroke, moving the caret and turning a simple amount into a fight. This input groups the digits the way the locale does as you type and puts the caret back after the same digit, so separators appear without the caret ever jumping; at rest the amount rolls into place when it changes. It understands currency fraction digits, including zero-decimal currencies, reports number or null instead of a formatted string, and adds min/max validation, keyboard stepping and a folding clear action to the shared Hairline field.

States

rest
The amount carries locale grouping and the currency’s decimal places; a new value rolls its digits into place the way it moved.
editing
Separators appear as you type and the caret stays after the digit it was on; the symbol and field stay fixed.
step
Arrow keys adjust the amount by step, Shift by ten steps, and keep the caret at the end.
invalid
An unreadable or out-of-range amount shakes once and explains what can be entered.
clear
The clear icon folds into the field, empties both the visible and submitted values, and keeps focus.

Usage

usage.tsx
import { CurrencyInput } from "@/components/currency-input";<CurrencyInput  label="Monthly price"  value={price}  onValueChange={setPrice}  currency="USD"  locale="en-US"  min={0}  step={5}  clearable/>

Works with

A plan price with an annual total

The callback receives a number, so calculations and requests do not need to strip symbols or parse formatted text again.

example.tsx
"use client";import * as React from "react";import { CurrencyInput } from "@/components/currency-input";export function PlanPrice() {  const [monthly, setMonthly] = React.useState<number | null>(24);  const annual = monthly === null ? 0 : monthly * 12;  return (    <div>      <CurrencyInput        label="Monthly price"        name="monthlyPrice"        value={monthly}        onValueChange={setMonthly}        currency="EUR"        locale="de-DE"        min={0}        step={1}      />      <output>Annual total: {annual.toFixed(2)} EUR</output>    </div>  );}

Props

value / defaultValue
number | null
The numeric amount; null means empty.
onValueChange
(value: number | null) => void
Reports valid edits, steps and clearing.
onValueCommit
(value: number | null) => void
Runs when a draft, keyboard step or clear settles.
locale / currency= "en-US" / "USD"
string / string
Intl locale and ISO currency code.
min / max / step= -Infinity / Infinity / 1
number
Allowed range and Arrow Up/Down increment.
name
string
Submits the unformatted number through a hidden input.
clearable= false
boolean
Adds a folding clear button when there is content.
size= "md"
"sm" | "md"
28px or 36px field height.
label / hint / error / placeholder
ReactNode / ReactNode / ReactNode / string
Shared field copy and external validation.
required / disabled / id / className
boolean / boolean / string / string
Standard form and layout attributes.

Accessibility and motion

  • The default en-US locale is intentional for deterministic server rendering; pass the visitor’s locale when it is known.
  • The input uses inputMode="decimal" and a text draft rather than the browser’s number control. At rest a NumberRoll draws the amount over the field; screen readers read the field itself.
  • Values are rounded to the currency’s fraction digits on blur or Enter. Arrow stepping also respects decimal step precision.
  • Reduced motion removes the clear-button width transition, the limit bump and the digit roll.

Requirements

React 19, Tailwind CSS v4 and shadcn/ui theme variables (any style, light and dark). Icons from lucide-react.

The CLI also installs Number roll, Text morph.

Source

"use client";import * as React from "react";import { Field, fieldSurface, useFieldIds, useShake, type FieldSize } from "./field";import { NumberRoll } from "./number-roll";import { TextMorph } from "./text-morph";import { EASE_OUT, interactionIcon, useInteractionReducedMotion } from "./ui-interaction-motion";export interface CurrencyInputProps {  value?: number | null;  defaultValue?: number | null;  onValueChange?: (value: number | null) => void;  onValueCommit?: (value: number | null) => void;  locale?: string;  currency?: string;  min?: number;  max?: number;  step?: number;  label?: React.ReactNode;  hint?: React.ReactNode;  error?: React.ReactNode;  placeholder?: string;  clearable?: boolean;  required?: boolean;  disabled?: boolean;  name?: string;  size?: FieldSize;  id?: string;  className?: string;}function ClearIcon() {  return (    <svg viewBox="0 0 16 16" fill="none" aria-hidden="true" className="size-3.5">      <path d="M4.5 4.5l7 7M11.5 4.5l-7 7" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" />    </svg>  );}export function CurrencyInput({  value,  defaultValue = null,  onValueChange,  onValueCommit,  locale = "en-US",  currency = "USD",  min = -Infinity,  max = Infinity,  step = 1,  label,  hint,  error,  placeholder,  clearable = false,  required,  disabled,  name,  size = "md",  id,  className = "",}: CurrencyInputProps) {  const reduced = useInteractionReducedMotion();  const ids = useFieldIds(id);  const input = React.useRef<HTMLInputElement>(null);  const [own, setOwn] = React.useState<number | null>(defaultValue);  const current = value !== undefined ? value : own;  const [draft, setDraft] = React.useState<string | null>(null);  const [badInput, setBadInput] = React.useState<string | null>(null);  const currencyFormat = React.useMemo(() => new Intl.NumberFormat(locale, { style: "currency", currency }), [locale, currency]);  const fractionDigits = currencyFormat.resolvedOptions().maximumFractionDigits ?? 2;  const numberFormat = React.useMemo(    () => new Intl.NumberFormat(locale, { minimumFractionDigits: fractionDigits, maximumFractionDigits: fractionDigits }),    [locale, fractionDigits],  );  const currencyParts = React.useMemo(() => currencyFormat.formatToParts(1234.5), [currencyFormat]);  const symbol = currencyParts.filter((part) => part.type === "currency").map((part) => part.value).join("");  const currencyIndex = currencyParts.findIndex((part) => part.type === "currency");  const numberIndex = currencyParts.findIndex((part) => part.type === "integer");  const symbolFirst = currencyIndex < numberIndex;  const separators = React.useMemo(() => new Intl.NumberFormat(locale, { maximumFractionDigits: 1 }).formatToParts(12345.6), [locale]);  const group = separators.find((part) => part.type === "group")?.value ?? ",";  const decimal = separators.find((part) => part.type === "decimal")?.value ?? ".";  const sm = size === "sm";  const integerFormat = React.useMemo(() => new Intl.NumberFormat(locale, { maximumFractionDigits: 0 }), [locale]);  const [focused, setFocused] = React.useState(false);  const caret = React.useRef<number | null>(null);  /*   * What the field shows while typing: the integer part grouped as the locale groups it, the decimals as typed (no   * more than the currency allows). Separators appear under the caret without moving it: the caret is put back after   * the same number of digits it had before.   */  const live = (text: string) => {    const negative = /^\s*-/.test(text);    const at = fractionDigits > 0 ? text.lastIndexOf(decimal) : -1;    const whole = (at >= 0 ? text.slice(0, at) : text).replace(/\D/g, "").replace(/^0+(?=\d)/, "");    const fraction = at >= 0 ? text.slice(at + decimal.length).replace(/\D/g, "").slice(0, fractionDigits) : "";    const grouped = whole ? integerFormat.format(Number(whole)) : "";    return `${negative && min < 0 ? "-" : ""}${grouped}${at >= 0 ? decimal + fraction : ""}`;  };  /** How many digits, signs and decimal marks come before `end`: the caret's place, ignoring separators. */  const significant = (text: string, end: number) => {    let count = 0;    for (let i = 0; i < end; i++) if (/[\d-]/.test(text[i]) || text.startsWith(decimal, i)) count++;    return count;  };  const caretAfter = (text: string, count: number) => {    if (count <= 0) return 0;    let seen = 0;    for (let i = 0; i < text.length; i++) {      if (/[\d-]/.test(text[i]) || text.startsWith(decimal, i)) seen++;      if (seen === count) return i + 1;    }    return text.length;  };  React.useLayoutEffect(() => {    if (caret.current === null || !input.current) return;    input.current.setSelectionRange(caret.current, caret.current);    caret.current = null;  });  const parseAmount = (text: string): number | null => {    let normalised = text.trim().replaceAll(symbol, "").replace(/\s/g, "");    if (group) normalised = normalised.replaceAll(group, "");    if (decimal !== ".") normalised = normalised.replaceAll(decimal, ".");    if (!/^[+-]?(?:\d+\.?\d*|\.\d+)$/.test(normalised)) return null;    const parsed = Number(normalised);    return Number.isFinite(parsed) ? parsed : null;  };  const round = (amount: number) => Number(amount.toFixed(Math.max(fractionDigits, String(step).split(".")[1]?.length ?? 0)));  const store = (next: number | null, notify: boolean) => {    if (value === undefined) setOwn(next);    if (notify) onValueChange?.(next);  };  const settle = () => {    if (draft === null) return true;    const text = draft.trim();    if (!text) {      store(null, false);      onValueCommit?.(null);      setDraft(null);      setBadInput(null);      return true;    }    const parsed = parseAmount(text);    if (parsed === null) {      setBadInput("Enter a valid amount.");      return false;    }    if (parsed < min || parsed > max) {      const range = Number.isFinite(min) && Number.isFinite(max) ? `between ${numberFormat.format(min)} and ${numberFormat.format(max)}` : Number.isFinite(min) ? `at least ${numberFormat.format(min)}` : `no more than ${numberFormat.format(max)}`;      setBadInput(`Use an amount ${range}.`);      return false;    }    const next = Number(parsed.toFixed(fractionDigits));    store(next, next !== current);    onValueCommit?.(next);    setDraft(null);    setBadInput(null);    return true;  };  const bump = () => {    if (reduced) return;    input.current?.parentElement?.animate(      [{ transform: "none" }, { transform: "translateX(-3px)" }, { transform: "translateX(3px)" }, { transform: "translateX(-1px)" }, { transform: "none" }],      { duration: 280, easing: "ease-out" },    );  };  const stepBy = (direction: 1 | -1, multiplier = 1) => {    const typed = draft !== null ? parseAmount(draft) : null;    const base = typed ?? current ?? 0;    const next = round(Math.min(max, Math.max(min, base + direction * step * multiplier)));    if (next === current || next === typed) {      bump();      return;    }    store(next, true);    onValueCommit?.(next);    setDraft(live(String(next).replace(".", decimal)));    setBadInput(null);    requestAnimationFrame(() => {      const length = input.current?.value.length ?? 0;      input.current?.setSelectionRange(length, length);    });  };  const shown = draft ?? (current === null ? "" : numberFormat.format(current));  // At rest the amount is drawn by NumberRoll over the field (same box, same type), so a new value rolls into place.  const rolling = !focused && draft === null && current !== null;  const showClear = clearable && !disabled && shown.length > 0;  const describedBy = [hint && !error && !badInput ? ids.hint : null, error || badInput ? ids.error : null].filter(Boolean).join(" ") || undefined;  const shakeRef = useShake<HTMLDivElement>(!!error || !!badInput);  const symbolNode = (    <span className={`flex shrink-0 items-center text-muted-foreground ${sm ? "text-[12px]" : "text-[13px]"}`}>      <TextMorph animateWidth={false}>{symbol}</TextMorph>    </span>  );  return (    <Field id={ids.id} label={label} hint={hint} error={error ?? badInput} required={required} className={className}>      <div ref={shakeRef} className={`${fieldSurface({ invalid: !!error || !!badInput, disabled })} ${sm ? "h-7 text-[16px] sm:text-[12.5px]" : "h-9 text-[16px] sm:text-[13.5px]"}`}>        {symbolFirst && <span className={sm ? "pl-3" : "pl-4"}>{symbolNode}</span>}        <span className="relative flex h-full min-w-0 flex-1">        <input          ref={input}          id={ids.id}          value={shown}          inputMode="decimal"          autoComplete="off"          spellCheck={false}          required={required}          disabled={disabled}          placeholder={placeholder ?? numberFormat.format(0)}          aria-invalid={error || badInput ? true : undefined}          aria-describedby={describedBy}          onFocus={() => {            setFocused(true);            setDraft(current === null ? "" : live(String(current).replace(".", decimal)));            setBadInput(null);          }}          onChange={(e) => {            const raw = e.target.value;            const nextText = live(raw);            caret.current = caretAfter(nextText, significant(raw, e.target.selectionStart ?? raw.length));            setDraft(nextText);            setBadInput(null);            const parsed = parseAmount(nextText);            if (!nextText.trim()) store(null, true);            else if (parsed !== null) store(parsed, true);          }}          onBlur={() => {            setFocused(false);            settle();          }}          onKeyDown={(e) => {            if (e.key === "Enter") {              e.preventDefault();              settle();            } else if (e.key === "Escape") {              e.preventDefault();              setDraft(null);              setBadInput(null);            } else if (e.key === "ArrowUp" || e.key === "ArrowDown") {              e.preventDefault();              stepBy(e.key === "ArrowUp" ? 1 : -1, e.shiftKey ? 10 : 1);            }          }}          className={`h-full w-full min-w-0 bg-transparent tabular-nums outline-none placeholder:text-muted-foreground/70 ${sm ? "px-2.5" : "px-3"} ${showClear ? "pr-1" : ""} ${rolling ? "text-transparent" : ""}`}        />        {rolling && (          <span aria-hidden="true" className={`pointer-events-none absolute inset-y-0 left-0 flex items-center tabular-nums text-foreground ${sm ? "px-2.5" : "px-3"}`}>            <NumberRoll value={current} locales={locale} format={{ minimumFractionDigits: fractionDigits, maximumFractionDigits: fractionDigits }} />          </span>        )}        </span>        {!symbolFirst && <span className={showClear ? "" : sm ? "pr-3" : "pr-4"}>{symbolNode}</span>}        {clearable && (          <span className="grid shrink-0" style={{ gridTemplateColumns: showClear ? "1fr" : "0fr", transition: reduced ? "none" : `grid-template-columns 320ms ${EASE_OUT}` }}>            <span className="min-w-0 overflow-hidden">              <button                type="button"                tabIndex={showClear ? 0 : -1}                aria-hidden={!showClear}                aria-label="Clear amount"                onClick={() => {                  store(null, true);                  onValueCommit?.(null);                  setDraft("");                  setBadInput(null);                  input.current?.focus();                }}                className={`mr-1 flex items-center justify-center rounded-full text-muted-foreground cursor-pointer outline-none hover:bg-accent hover:text-foreground focus-visible:shadow-[inset_0_0_0_2px_var(--ring)] ${sm ? "size-5" : "size-7"}`}                style={interactionIcon(showClear, reduced)}              >                <ClearIcon />              </button>            </span>          </span>        )}      </div>      {name && <input type="hidden" name={name} value={current ?? ""} />}    </Field>  );}export default CurrencyInput;

Registry item: /r/currency-input.json