@canutin/svelte-currency-input

中文文档
1.1.2发布于 2026/06/23MITTypeScriptES Module零依赖构建来源已验证近 30 天下载 2792

A fully-featured currency input component for Svelte 5 that handles formatting, localization, and validation

原始使用文档
文档目录21 节
  1. Features
  2. Installation
  3. Usage
  4. How it works
  5. API
  6. Props
  7. Types
  8. Examples
  9. International currencies
  10. Decimal precision
  11. Min, max, and step
  12. Custom prefix and suffix
  13. Abbreviations
  14. Callbacks
  15. Input element reference
  16. Styling
  17. Exported utilities
  18. formatValue options
  19. Svelte 4
  20. Contributing
  21. License

svelte-currency-input

A fully-featured currency input component for Svelte 5 that handles formatting, localization, and validation as you type.

svelte-currency-input examples

👩‍💻 Play with it in the live demo


Features

  • Formats positive and negative values
  • Leverages Intl.NumberFormat for localizing currency denominations
  • Supports abbreviations (k, m, b) for quick input
  • Configurable decimal precision with multiple control options
  • Min/max constraints with arrow key stepping
  • Custom prefix and suffix support
  • Zero built-in styles — works with Tailwind, vanilla CSS, or any framework
  • Simple, single <input> element (no wrapper)
  • Full TypeScript support
  • Lightweight — ~3.6KB gzipped with no runtime dependencies
  • API and logic heavily inspired by @cchanxzy's react-currency-input-field

Installation

# bun
bun add @canutin/svelte-currency-input

# pnpm
pnpm add @canutin/svelte-currency-input

# npm
npm install @canutin/svelte-currency-input

# yarn
yarn add @canutin/svelte-currency-input

Usage

<script lang="ts">
    import { CurrencyInput } from '@canutin/svelte-currency-input';

    let value = $state('1234.56');
</script>

<CurrencyInput bind:value intlConfig={{ locale: 'en-US', currency: 'USD' }} />

The input displays $1,234.56 while value contains the raw string "1234.56".

How it works

The component renders a single <input> element. The value prop is a string representing the unformatted number:

  • "" = empty input
  • "0" = zero
  • "1234.56" = the number 1234.56

The formatted display (e.g., $1,234.56) is handled internally. For form submissions where you need the raw value, you can add a hidden input:

<form>
    <CurrencyInput bind:value name="display" />
    <input type="hidden" name="amount" {value} />
</form>

API

Props

PropTypeDefaultDescription
valuestring''Bindable raw value (e.g., "1234.56")
intlConfigIntlConfigundefinedLocale and currency configuration
prefixstringFrom localeOverride the currency prefix
suffixstring''Override the currency suffix
decimalSeparatorstringFrom localeOverride the decimal separator
groupSeparatorstringFrom localeOverride the grouping separator
disableGroupSeparatorsbooleanfalseDisable thousand separators
allowDecimalsbooleantrueAllow decimal values
decimalsLimitnumber2Max decimal digits while typing
decimalScalenumberundefinedPad/trim decimals on blur
fixedDecimalLengthnumberundefinedFixed decimal input (e.g., 2: typing 123 → 1.23)
allowNegativeValuebooleantrueAllow negative values
minnumberundefinedMinimum value (enforced on arrow key step)
maxnumberundefinedMaximum value (enforced on arrow key step)
maxLengthnumberundefinedMax characters (excluding formatting)
stepnumberundefinedArrow key increment/decrement
disableAbbreviationsbooleanfalseDisable k/m/b abbreviations
formatValueOnBlurbooleantrueApply formatting when input loses focus
transformRawValue(value: string) => stringundefinedTransform the raw value before processing
oninputvalue(values: CurrencyInputValues) => voidundefinedCallback on every input change
onchangevalue(values: CurrencyInputValues) => voidundefinedCallback on blur/commit
refHTMLInputElement | nullnullBindable reference to the input element
classstringundefinedCSS class(es) for the input
...restPropsHTMLInputAttributes—All standard input attributes (id, name, placeholder, disabled, required, etc.)

Types

interface IntlConfig {
    locale: string;
    currency?: string;
    // Also accepts other Intl.NumberFormatOptions
}

interface CurrencyInputValues {
    float: number | null; // Parsed number or null if empty
    formatted: string; // Display value: "$1,234.56"
    value: string; // Raw value: "1234.56"
}

Examples

International currencies

<CurrencyInput bind:value intlConfig={{ locale: 'de-DE', currency: 'EUR' }} />
<!-- Displays: 1.234,56 € -->

Decimal precision

<!-- Limit to 2 decimals while typing, pad to 2 on blur -->
<CurrencyInput
    bind:value
    intlConfig={{ locale: 'en-US', currency: 'USD' }}
    decimalsLimit={2}
    decimalScale={2}
/>

Min, max, and step

<!-- Use arrow keys to increment/decrement by 10, constrained to 0-100 -->
<CurrencyInput
    bind:value
    intlConfig={{ locale: 'en-US', currency: 'USD' }}
    min={0}
    max={100}
    step={10}
/>

Custom prefix and suffix

<!-- Points system -->
<CurrencyInput bind:value suffix=" pts" decimalsLimit={0} />

<!-- Bitcoin -->
<CurrencyInput bind:value prefix="₿ " decimalsLimit={8} />

Abbreviations

Type 1k, 2.5m, or 1b to quickly enter large numbers:

<CurrencyInput
    bind:value
    intlConfig={{ locale: 'en-US', currency: 'USD' }}
    placeholder="Try 1k, 2.5m, or 1b"
/>
<!-- Typing "2.5m" results in value="2500000" -->

Callbacks

<CurrencyInput
    bind:value
    intlConfig={{ locale: 'en-US', currency: 'USD' }}
    oninputvalue={({ float, formatted, value }) => {
        console.log('On input:', { float, formatted, value });
    }}
    onchangevalue={({ float, formatted, value }) => {
        console.log('On blur:', { float, formatted, value });
    }}
/>

Input element reference

<script>
    let inputRef = $state(null);

    function focusInput() {
        inputRef?.focus();
    }
</script>

<CurrencyInput bind:ref={inputRef} bind:value />
<button onclick={focusInput}>Focus</button>

Styling

The component renders a single <input> element with no built-in styles. You can use the class prop to style it:

<!-- Tailwind CSS -->
<CurrencyInput bind:value class="rounded border px-3 py-2 focus:ring-2 focus:ring-blue-500" />

<!-- Custom CSS class -->
<CurrencyInput bind:value class="my-currency-input" />

For dynamic styling based on value (positive/negative/zero), use the callback:

<script>
    let value = $state('');
    let colorClass = $state('');

    function updateStyle({ float }) {
        if (float === null || float === 0) colorClass = 'text-gray-500';
        else if (float > 0) colorClass = 'text-green-600';
        else colorClass = 'text-red-600';
    }
</script>

<CurrencyInput bind:value class="border px-3 py-2 {colorClass}" oninputvalue={updateStyle} />

Exported utilities

The package exports utility functions for use outside the component:

import {
    formatValue,
    getLocaleConfig,
    cleanValue,
    parseAbbrValue,
    abbrValue
} from '@canutin/svelte-currency-input';

// Format a value with locale
const formatted = formatValue({
    value: '1234.56',
    intlConfig: { locale: 'en-US', currency: 'USD' }
});
// → "$1,234.56"

// Get locale configuration
const config = getLocaleConfig({ locale: 'de-DE', currency: 'EUR' });
// → { decimalSeparator: ',', groupSeparator: '.', prefix: '', suffix: ' €', ... }

// Parse abbreviations
const expanded = parseAbbrValue('2.5m', 'en-US');
// → "2500000"

formatValue options

OptionTypeDefaultDescription
valuestring—The value to format
intlConfigIntlConfigundefinedLocale and currency configuration
decimalScalenumberundefinedNumber of decimal places
decimalSeparatorstringFrom localeOverride the decimal separator
groupSeparatorstringFrom localeOverride the grouping separator
disableGroupSeparatorsbooleanfalseDisable thousand separators
prefixstringFrom localeOverride the currency prefix
suffixstring''Override the currency suffix
roundValuebooleanfalseRound to decimalScale instead of truncating

By default, formatValue truncates decimals to decimalScale. Set roundValue: true to round instead, which is useful when formatting computed values with floating-point precision artifacts:

// Default: truncates
formatValue({
    value: '87.5',
    intlConfig: { locale: 'en-US', currency: 'USD' },
    decimalScale: 0
});
// → "$87"

// With roundValue: rounds
formatValue({
    value: '87.5',
    intlConfig: { locale: 'en-US', currency: 'USD' },
    decimalScale: 0,
    roundValue: true
});
// → "$88"

// Useful for computed values with floating-point issues
const sum = 500.75 + 300.5 - 200.25 - 150.33; // = 450.66999999999996
formatValue({
    value: String(sum),
    intlConfig: { locale: 'en-US', currency: 'USD' },
    decimalScale: 2,
    roundValue: true
});
// → "$450.67" (without roundValue, would be "$450.66")

Svelte 4

For Svelte 4 support, use the 0.x version:

npm install @canutin/svelte-currency-input@0

If you're upgrading from v0.x, see the migration guide.

Contributing

See CONTRIBUTING.md for development setup, testing, and contribution guidelines.

License

MIT

版本与发布记录

@canutin/svelte-currency-input 共发布 43 个版本,首次发布于 2022/09/15;过去 12 个月发布了 6 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
1.1.2latest2026/06/234 个月前
1.1.12026/01/0310 个月前
1.1.02026/01/0310 个月前
1.0.02026/01/0310 个月前
1.0.0-next.8next2026/01/0310 个月前
1.0.0-next.72026/01/0310 个月前

关于 @canutin/svelte-currency-input 的常见问题

@canutin/svelte-currency-input 是什么?

A fully-featured currency input component for Svelte 5 that handles formatting, localization, and validation

如何安装 @canutin/svelte-currency-input?

在项目目录运行 npm install @canutin/svelte-currency-input,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:svelte(^5.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@canutin/svelte-currency-input 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@canutin/svelte-currency-input 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@canutin/svelte-currency-input 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@canutin/svelte-currency-input 可以商用吗?

@canutin/svelte-currency-input 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@canutin/svelte-currency-input 的下载量有多少?

根据 npm 官方下载统计,@canutin/svelte-currency-input 在 2026/10/09 – 2026/11/07 这 30 天内被下载 2,792 次,日均约 93 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@canutin/svelte-currency-input 还在维护吗?

最新版本 1.1.2 发布于 2026/06/23(4 个月前);至今共发布 43 个版本,其中过去 12 个月发布了 6 个;首次发布于 2022/09/15。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。