A lightweight, reactive number formatter utility for Svelte + TypeScript.
Supports:
12,345.67
, $1,000.00
, etc.)12345.67
)npm install svelte-number-formatter
๐ GitHub Repository: github.com/dev-henen/svelte-number-formatter
import { NumberFormatter } from 'svelte-number-formatter';
const formatter = new NumberFormatter();
<script lang="ts">
import { NumberFormatter } from 'svelte-number-formatter';
const formatter = new NumberFormatter('', {
style: 'decimal',
decimals: 2
});
</script>
<input bind:value={formatter.handler} />
<p>Raw: {formatter.raw}</p>
<p>Formatted: {formatter.formatted}</p>
or
<script lang="ts">
import { NumberFormatter } from 'svelte-number-formatter';
const formatter = new NumberFormatter('', {
style: 'decimal',
decimals: 2
});
let value = formatter.formatted;
// Sync user input into formatter
$: formatter.handler = value;
</script>
<input bind:value={value} />
<p>Raw: {formatter.raw}</p>
<p>Formatted: {formatter.formatted}</p>
constructor(initial?: string, options?: FormatOptions)
Create a new formatter with optional initial value and format options.
Property | Type | Description |
---|---|---|
handler |
string |
Input setter that auto-updates raw + formatted |
raw |
string |
The numeric value stripped of symbols |
formatted |
string |
The value formatted for display (12,345.67 ) |
๐ Setting
.handler = "12345"
will automatically set both.raw
and.formatted
.
setOptions(options: Partial<FormatOptions>)
Update locale, decimals, grouping, or currency format.
formatter.setOptions({
style: 'currency',
currency: 'USD',
decimals: 2
});
{
locale?: string; // e.g., "en-US"
useGrouping?: boolean; // commas (true by default)
decimals?: number; // number of decimal places (default 0)
currency?: string; // e.g., "USD"
style?: 'decimal' | 'currency'; // default: 'decimal'
}
reset()
Clear both raw and formatted values.
formatter.reset();
format(value: string | number): string
Format a raw number programmatically:
formatter.format("123456.789"); // โ "123,456.79" or "$123,456.79"
const formatter = new NumberFormatter('', {
style: 'currency',
currency: 'USD',
decimals: 2
});
formatter.handler = '456789.123';
console.log(formatter.formatted); // "$456,789.12"
console.log(formatter.raw); // "456789.123"
<input type="text" />
bind:value
directly with .formatted
; use a local value
and sync via $:
https://www.npmjs.com/package/svelte-number-formatter
MIT ยฉ dev-henen
use:numberFormatter
Svelte actionformatter.subscribe()
)