Web InnoventixFreeCode

Currency Input

Original · free

currency input with formatting

byWeb InnoventixReact + Tailwind
inpcurrencyinputs
Open

Copy prompt gives Claude Code, Cursor or v0 a ready-to-paste prompt that recreates this exact component.

npx shadcn@latest add https://webinnoventix.com/r/inp-currency.json
inp-currency.tsx
"use client";

import { useState, useRef, useEffect } from "react";
import type { ChangeEvent, ReactNode } from "react";
import { motion, AnimatePresence, useReducedMotion } from "motion/react";

type CurrencyCode = "USD" | "EUR" | "GBP" | "JPY" | "INR";

interface CurrencyConfig {
  code: CurrencyCode;
  symbol: string;
  name: string;
  locale: string;
  decimals: number;
  symbolPosition: "prefix" | "suffix";
}

const CURRENCIES: Record<CurrencyCode, CurrencyConfig> = {
  USD: { code: "USD", symbol: "$", name: "US Dollar", locale: "en-US", decimals: 2, symbolPosition: "prefix" },
  GBP: { code: "GBP", symbol: "£", name: "British Pound", locale: "en-US", decimals: 2, symbolPosition: "prefix" },
  EUR: { code: "EUR", symbol: "€", name: "Euro", locale: "en-US", decimals: 2, symbolPosition: "suffix" },
  INR: { code: "INR", symbol: "₹", name: "Indian Rupee", locale: "en-IN", decimals: 2, symbolPosition: "prefix" },
  JPY: { code: "JPY", symbol: "¥", name: "Japanese Yen", locale: "en-US", decimals: 0, symbolPosition: "prefix" },
};

const CURRENCY_ORDER: CurrencyCode[] = ["USD", "EUR", "GBP", "INR", "JPY"];

/** Keep only digits and a single decimal point, and clamp fractional digits. */
function cleanRaw(input: string, decimals: number): string {
  let s = input.replace(/[^\d.]/g, "");
  const firstDot = s.indexOf(".");
  if (firstDot !== -1) {
    s = s.slice(0, firstDot + 1) + s.slice(firstDot + 1).replace(/\./g, "");
  }
  if (decimals === 0) return s.replace(/\./g, "");
  if (s.includes(".")) {
    const [intPart, decPart] = s.split(".");
    return `${intPart}.${decPart.slice(0, decimals)}`;
  }
  return s;
}

/** Group the integer portion using the locale's grouping style (comma / lakh). */
function groupInteger(intDigits: string, locale: string): string {
  const trimmed = intDigits.replace(/^0+(?=\d)/, "");
  if (trimmed === "") return "0";
  const asNumber = Number(trimmed);
  if (!Number.isFinite(asNumber)) return trimmed;
  return new Intl.NumberFormat(locale, { maximumFractionDigits: 0, useGrouping: true }).format(asNumber);
}

/** Turn a cleaned raw string into a grouped display string (no currency symbol). */
function formatDisplay(raw: string, config: CurrencyConfig): string {
  if (raw === "") return "";
  const hasDot = raw.includes(".");
  const [intPart, decPart = ""] = raw.split(".");
  let out = groupInteger(intPart, config.locale);
  if (config.decimals > 0 && hasDot) out += `.${decPart}`;
  return out;
}

function parseAmount(raw: string): number {
  if (raw === "" || raw === ".") return 0;
  const n = Number(raw);
  return Number.isFinite(n) ? n : 0;
}

const SIGNIFICANT = /[0-9.]/;

/** Count digits + decimal point up to a caret index. */
function significantCount(str: string, upto: number): number {
  let count = 0;
  for (let i = 0; i < upto && i < str.length; i++) {
    if (SIGNIFICANT.test(str[i])) count += 1;
  }
  return count;
}

/** Find the caret index in a new string after N significant chars have passed. */
function caretForSignificant(str: string, target: number): number {
  if (target <= 0) return 0;
  let seen = 0;
  for (let i = 0; i < str.length; i++) {
    if (SIGNIFICANT.test(str[i])) {
      seen += 1;
      if (seen === target) return i + 1;
    }
  }
  return str.length;
}

function formatCurrency(value: number, config: CurrencyConfig): string {
  return new Intl.NumberFormat(config.locale, {
    style: "currency",
    currency: config.code,
    minimumFractionDigits: config.decimals,
    maximumFractionDigits: config.decimals,
  }).format(value);
}

interface CurrencyFieldProps {
  id: string;
  label: string;
  config: CurrencyConfig;
  value: string;
  onValueChange: (raw: string) => void;
  helper?: string;
  error?: string | null;
  size?: "md" | "lg";
}

function CurrencyField({ id, label, config, value, onValueChange, helper, error, size = "md" }: CurrencyFieldProps) {
  const inputRef = useRef<HTMLInputElement | null>(null);
  const caretRef = useRef<number | null>(null);

  useEffect(() => {
    if (caretRef.current !== null && inputRef.current) {
      const pos = caretRef.current;
      inputRef.current.setSelectionRange(pos, pos);
      caretRef.current = null;
    }
  });

  const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
    const el = e.target;
    const previous = el.value;
    const caret = el.selectionStart ?? previous.length;
    const sig = significantCount(previous, caret);
    const raw = cleanRaw(previous, config.decimals);
    const display = formatDisplay(raw, config);
    caretRef.current = caretForSignificant(display, sig);
    onValueChange(raw);
  };

  const display = formatDisplay(value, config);
  const placeholder = config.decimals > 0 ? `0.${"0".repeat(config.decimals)}` : "0";
  const describedBy = error ? `${id}-error` : helper ? `${id}-help` : undefined;
  const hasError = Boolean(error);

  const sizeInput = size === "lg" ? "text-3xl py-4" : "text-xl py-3";
  const sizeSymbol = size === "lg" ? "text-2xl" : "text-lg";

  const wrapper = [
    "flex items-center gap-2 rounded-2xl border bg-white px-4 transition-colors",
    "dark:bg-slate-900",
    hasError
      ? "border-rose-400 focus-within:border-rose-500 focus-within:ring-2 focus-within:ring-rose-500/40 dark:border-rose-500/70"
      : "border-slate-300 focus-within:border-indigo-500 focus-within:ring-2 focus-within:ring-indigo-500/40 dark:border-slate-700 dark:focus-within:border-indigo-400",
  ].join(" ");

  const symbolEl = (
    <span aria-hidden="true" className={`shrink-0 font-semibold tabular-nums ${sizeSymbol} text-slate-400 dark:text-slate-500`}>
      {config.symbol}
    </span>
  );

  return (
    <div className="w-full">
      <label htmlFor={id} className="mb-2 block text-sm font-medium text-slate-700 dark:text-slate-300">
        {label} <span className="text-slate-400 dark:text-slate-500">· {config.name}</span>
      </label>
      <div className={wrapper}>
        {config.symbolPosition === "prefix" && symbolEl}
        <input
          ref={inputRef}
          id={id}
          type="text"
          inputMode="decimal"
          autoComplete="off"
          spellCheck={false}
          enterKeyHint="done"
          value={display}
          onChange={handleChange}
          placeholder={placeholder}
          aria-invalid={hasError}
          aria-describedby={describedBy}
          className={`w-full min-w-0 bg-transparent font-semibold tabular-nums tracking-tight text-slate-900 outline-none placeholder:font-normal placeholder:text-slate-300 dark:text-slate-50 dark:placeholder:text-slate-600 ${sizeInput}`}
        />
        {config.symbolPosition === "suffix" && symbolEl}
        <span className="shrink-0 rounded-md bg-slate-100 px-2 py-0.5 text-xs font-semibold tracking-wide text-slate-500 dark:bg-slate-800 dark:text-slate-400">
          {config.code}
        </span>
      </div>
      <div className="mt-2 min-h-[1.25rem]">
        <AnimatePresence mode="wait" initial={false}>
          {error ? (
            <motion.p
              key="error"
              id={`${id}-error`}
              initial={{ opacity: 0, y: -4 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -4 }}
              transition={{ duration: 0.18 }}
              className="flex items-center gap-1.5 text-sm font-medium text-rose-600 dark:text-rose-400"
            >
              <svg viewBox="0 0 20 20" width="15" height="15" fill="currentColor" aria-hidden="true">
                <path
                  fillRule="evenodd"
                  d="M10 18a8 8 0 100-16 8 8 0 000 16zM9 7a1 1 0 112 0v4a1 1 0 11-2 0V7zm1 8a1.1 1.1 0 100-2.2 1.1 1.1 0 000 2.2z"
                  clipRule="evenodd"
                />
              </svg>
              {error}
            </motion.p>
          ) : helper ? (
            <p key="help" id={`${id}-help`} className="text-sm text-slate-500 dark:text-slate-400">
              {helper}
            </p>
          ) : null}
        </AnimatePresence>
      </div>
    </div>
  );
}

function Card({ title, caption, children }: { title: string; caption: string; children: ReactNode }) {
  return (
    <div className="inpcur-rise rounded-3xl border border-slate-200/80 bg-white/90 p-6 shadow-sm backdrop-blur-sm sm:p-7 dark:border-slate-800 dark:bg-slate-900/70">
      <div className="mb-5">
        <h3 className="text-base font-semibold text-slate-900 dark:text-slate-50">{title}</h3>
        <p className="mt-1 text-sm text-slate-500 dark:text-slate-400">{caption}</p>
      </div>
      {children}
    </div>
  );
}

export default function InpCurrency() {
  const reduce = useReducedMotion();

  const [currency, setCurrency] = useState<CurrencyCode>("USD");
  const [payRaw, setPayRaw] = useState<string>("1499.00");
  const [budgetRaw, setBudgetRaw] = useState<string>("8750");
  const [eurRaw, setEurRaw] = useState<string>("29.00");
  const [jpyRaw, setJpyRaw] = useState<string>("48000");

  const payConfig = CURRENCIES[currency];
  const payValue = parseAmount(payRaw);

  const BUDGET_CAP = 10000;
  const budgetConfig = CURRENCIES.USD;
  const budgetValue = parseAmount(budgetRaw);
  const budgetError = budgetValue > BUDGET_CAP ? `That is over your ${formatCurrency(BUDGET_CAP, budgetConfig)} monthly cap.` : null;

  const handleCurrencyChange = (e: ChangeEvent<HTMLSelectElement>) => {
    const next = e.target.value as CurrencyCode;
    setCurrency(next);
    setPayRaw((prev) => cleanRaw(prev, CURRENCIES[next].decimals));
  };

  const chipDeltas = payConfig.decimals === 0 ? [1000, 5000, 10000] : [25, 50, 100];
  const addToPay = (delta: number) => {
    const next = Math.max(0, payValue + delta);
    setPayRaw(next.toFixed(payConfig.decimals));
  };

  return (
    <section className="relative w-full overflow-hidden bg-slate-50 px-4 py-16 text-slate-900 sm:px-6 sm:py-24 dark:bg-slate-950 dark:text-slate-50">
      <style>{`
        @keyframes inpcur-rise {
          from { opacity: 0; transform: translateY(14px); }
          to { opacity: 1; transform: translateY(0); }
        }
        @keyframes inpcur-sheen {
          0% { background-position: -160% 0; }
          100% { background-position: 260% 0; }
        }
        @keyframes inpcur-pop {
          0% { transform: scale(1); }
          45% { transform: scale(1.05); }
          100% { transform: scale(1); }
        }
        .inpcur-rise { animation: inpcur-rise 0.6s cubic-bezier(0.22, 1, 0.36, 1) both; }
        .inpcur-rise:nth-child(2) { animation-delay: 0.08s; }
        .inpcur-rise:nth-child(3) { animation-delay: 0.16s; }
        .inpcur-badge {
          background-image: linear-gradient(110deg, transparent 30%, rgba(129,140,248,0.55) 50%, transparent 70%);
          background-size: 200% 100%;
          animation: inpcur-sheen 4.5s linear infinite;
        }
        .inpcur-pop { animation: inpcur-pop 0.28s ease-out; }
        @media (prefers-reduced-motion: reduce) {
          .inpcur-rise, .inpcur-badge, .inpcur-pop { animation: none !important; }
        }
      `}</style>

      {/* atmospheric background */}
      <div aria-hidden="true" className="pointer-events-none absolute inset-0">
        <div className="absolute -left-24 -top-24 h-72 w-72 rounded-full bg-indigo-300/30 blur-3xl dark:bg-indigo-600/15" />
        <div className="absolute -right-16 top-1/3 h-72 w-72 rounded-full bg-violet-300/25 blur-3xl dark:bg-violet-600/15" />
        <div
          className="absolute inset-0 opacity-[0.4] dark:opacity-[0.25]"
          style={{
            backgroundImage:
              "linear-gradient(to right, rgba(100,116,139,0.08) 1px, transparent 1px), linear-gradient(to bottom, rgba(100,116,139,0.08) 1px, transparent 1px)",
            backgroundSize: "42px 42px",
          }}
        />
      </div>

      <div className="relative mx-auto max-w-5xl">
        <header className="mb-10 max-w-2xl">
          <span className="relative inline-flex overflow-hidden rounded-full border border-indigo-200 bg-white px-3 py-1 text-xs font-semibold uppercase tracking-wider text-indigo-600 dark:border-indigo-500/30 dark:bg-slate-900 dark:text-indigo-300">
            <span className="relative z-10">Inputs · Currency</span>
            <span aria-hidden="true" className="inpcur-badge absolute inset-0" />
          </span>
          <h2 className="mt-4 text-3xl font-bold tracking-tight sm:text-4xl">Currency amount input</h2>
          <p className="mt-3 text-base text-slate-600 dark:text-slate-400">
            Live thousands-grouping that respects each locale, a caret that stays put while you type, and validation
            that reads out loud. Fully keyboard and screen-reader friendly.
          </p>
        </header>

        <div className="grid gap-6 lg:grid-cols-3">
          {/* Card 1 — selector + live total + quick add */}
          <div className="lg:col-span-3">
            <Card title="Checkout total" caption="Pick a currency and watch grouping adapt to its locale in real time.">
              <div className="grid gap-6 md:grid-cols-[1fr_1.1fr] md:items-start">
                <div>
                  <div className="mb-4">
                    <label htmlFor="pay-currency" className="mb-2 block text-sm font-medium text-slate-700 dark:text-slate-300">
                      Currency
                    </label>
                    <div className="relative">
                      <select
                        id="pay-currency"
                        value={currency}
                        onChange={handleCurrencyChange}
                        className="w-full appearance-none rounded-2xl border border-slate-300 bg-white px-4 py-3 pr-10 text-sm font-medium text-slate-900 outline-none transition-colors focus-visible:border-indigo-500 focus-visible:ring-2 focus-visible:ring-indigo-500/40 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-50"
                      >
                        {CURRENCY_ORDER.map((code) => (
                          <option key={code} value={code}>
                            {CURRENCIES[code].symbol}  {code} — {CURRENCIES[code].name}
                          </option>
                        ))}
                      </select>
                      <svg
                        aria-hidden="true"
                        viewBox="0 0 20 20"
                        className="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-slate-400"
                        width="18"
                        height="18"
                        fill="none"
                        stroke="currentColor"
                        strokeWidth="1.8"
                      >
                        <path d="M6 8l4 4 4-4" strokeLinecap="round" strokeLinejoin="round" />
                      </svg>
                    </div>
                  </div>

                  <CurrencyField
                    id="pay-amount"
                    label="Amount"
                    config={payConfig}
                    value={payRaw}
                    onValueChange={setPayRaw}
                    helper={payConfig.decimals === 0 ? "This currency has no minor units." : "Up to two decimal places."}
                    size="lg"
                  />

                  <div className="mt-4 flex flex-wrap gap-2">
                    {chipDeltas.map((delta) => (
                      <button
                        key={delta}
                        type="button"
                        onClick={() => addToPay(delta)}
                        className="rounded-full border border-slate-300 bg-white px-3.5 py-1.5 text-sm font-medium text-slate-700 transition-colors hover:border-indigo-400 hover:bg-indigo-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-indigo-500 focus-visible:ring-offset-2 focus-visible:ring-offset-white dark:border-slate-700 dark:bg-slate-800 dark:text-slate-200 dark:hover:border-indigo-500 dark:hover:bg-slate-700 dark:focus-visible:ring-offset-slate-900"
                      >
                        +{formatCurrency(delta, payConfig)}
                      </button>
                    ))}
                    <button
                      type="button"
                      onClick={() => setPayRaw("")}
                      className="rounded-full px-3.5 py-1.5 text-sm font-medium text-slate-500 transition-colors hover:text-rose-600 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-rose-500 focus-visible:ring-offset-2 focus-visible:ring-offset-white dark:text-slate-400 dark:hover:text-rose-400 dark:focus-visible:ring-offset-slate-900"
                    >
                      Clear
                    </button>
                  </div>
                </div>

                <div className="rounded-2xl bg-gradient-to-br from-indigo-600 to-violet-600 p-6 text-white shadow-lg shadow-indigo-500/20">
                  <p className="text-sm font-medium text-indigo-100">Amount due today</p>
                  <div className="mt-2">
                    <motion.span
                      key={`${currency}-${payValue}`}
                      initial={reduce ? false : { scale: 0.94, opacity: 0.5 }}
                      animate={{ scale: 1, opacity: 1 }}
                      transition={{ duration: 0.25, ease: "easeOut" }}
                      className="block text-4xl font-bold tabular-nums tracking-tight"
                    >
                      {formatCurrency(payValue, payConfig)}
                    </motion.span>
                  </div>
                  <dl className="mt-6 space-y-2 border-t border-white/20 pt-4 text-sm">
                    <div className="flex justify-between">
                      <dt className="text-indigo-100">Numeric value</dt>
                      <dd className="font-mono tabular-nums">{payValue}</dd>
                    </div>
                    <div className="flex justify-between">
                      <dt className="text-indigo-100">Currency</dt>
                      <dd className="font-medium">{payConfig.code} · {payConfig.name}</dd>
                    </div>
                    <div className="flex justify-between">
                      <dt className="text-indigo-100">Grouping</dt>
                      <dd className="font-medium">{payConfig.locale === "en-IN" ? "Lakh / crore" : "Thousands"}</dd>
                    </div>
                  </dl>
                </div>
              </div>
            </Card>
          </div>

          {/* Card 2 — validation against a cap */}
          <div className="lg:col-span-2">
            <Card title="Budget cap" caption="Enter a spend and get a live, announced error when it exceeds your limit.">
              <CurrencyField
                id="budget-amount"
                label="Monthly ad spend"
                config={budgetConfig}
                value={budgetRaw}
                onValueChange={setBudgetRaw}
                helper={`Maximum ${formatCurrency(BUDGET_CAP, budgetConfig)} per month.`}
                error={budgetError}
              />
              <div className="mt-2 h-2 w-full overflow-hidden rounded-full bg-slate-200 dark:bg-slate-800">
                <div
                  className={`h-full rounded-full transition-[width,background-color] duration-300 ${
                    budgetError ? "bg-rose-500" : "bg-emerald-500"
                  }`}
                  style={{ width: `${Math.min(100, (budgetValue / BUDGET_CAP) * 100)}%` }}
                />
              </div>
              <p className="mt-2 text-xs text-slate-500 dark:text-slate-400">
                {Math.min(100, Math.round((budgetValue / BUDGET_CAP) * 100))}% of cap used
              </p>
            </Card>
          </div>

          {/* Card 3 — decimals + suffix demonstration */}
          <div className="lg:col-span-1">
            <Card title="Placement & minor units" caption="Suffix symbols and zero-decimal currencies, handled.">
              <div className="space-y-5">
                <CurrencyField
                  id="eur-amount"
                  label="Plan price"
                  config={CURRENCIES.EUR}
                  value={eurRaw}
                  onValueChange={setEurRaw}
                  helper="Symbol sits after the number."
                />
                <CurrencyField
                  id="jpy-amount"
                  label="One-time fee"
                  config={CURRENCIES.JPY}
                  value={jpyRaw}
                  onValueChange={setJpyRaw}
                  helper="Yen takes no decimals."
                />
              </div>
            </Card>
          </div>
        </div>
      </div>
    </section>
  );
}

Dependencies

motion

Licence

Built by Web Innoventix. Free for personal and commercial use, no attribution required.

Built by Web Innoventix

Need a custom interface, a full website, or SEO that gets you cited by AI? We design, build and rank it end to end.

Get a free quote

Similar components

Browse all →