@favorodera/format-number
v1.0.0
Published
A TypeScript utility for formatting numbers with Intl.NumberFormat, supporting conditional compact notation
Maintainers
Readme
format-number
A TypeScript utility for formatting numbers with Intl.NumberFormat, supporting conditional compact notation based on thresholds.
Features
- Zero dependencies - Uses native
Intl.NumberFormat - TypeScript support - Full type definitions included
- Conditional compact notation - Format numbers compactly only when they exceed a threshold
- Internationalization - Supports all locales supported by
Intl.NumberFormat - Tree-shakeable - ESM and CommonJS builds available
Installation
npm install @favorodera/format-numberℹ️ For auto-import in Nuxt, add the following to your
nuxt.config.ts:imports: { presets: [ { from: '@favorodera/format-number', imports: [ { name: 'default', as: 'formatNumber' }, ], }, ], },
Usage
Basic Usage
import formatNumber from 'format-number'
// Basic formatting
formatNumber(1234.56) // "1,234.56"
formatNumber(1234.56, 'en-US', { style: 'currency', currency: 'USD' }) // "$1,234.56"Compact Notation
import formatNumber from 'format-number'
// Always compact
formatNumber(1234567, 'en-US', { notation: 'compact' }) // "1.2M"
// Conditional compact (only when value >= threshold)
formatNumber(1234, 'en-US', {
notation: 'compact',
compactThreshold: 10000
}) // "1,234" (not compact because 1234 < 10000)
formatNumber(123456, 'en-US', {
notation: 'compact',
compactThreshold: 10000
}) // "123K" (compact because 123456 >= 10000)Advanced Examples
import formatNumber from 'format-number'
// Percentage
formatNumber(0.1234, 'en-US', { style: 'percent' }) // "12%"
// Scientific notation
formatNumber(1234567, 'en-US', { notation: 'scientific' }) // "1.235E6"
// Different locales
formatNumber(1234.56, 'de-DE') // "1.234,56"
formatNumber(1234.56, 'fr-FR', { style: 'currency', currency: 'EUR' }) // "1 234,56 €"API
formatNumber(value, options, locales)
Parameters
value: number- The number to formatoptions?: FormatNumberOptions- Formatting options (optional)locales?: Intl.LocalesArgument- Locale(s) to use for formatting (optional)
Returns
string- The formatted number string
Options
The options parameter extends Intl.NumberFormatOptions with additional properties:
compactThreshold?: number- Whennotation: 'compact'is set, only apply compact notation if the value is >= this threshold
All standard Intl.NumberFormatOptions are supported:
style?: 'decimal' | 'currency' | 'percent' | 'unit'currency?: stringcurrencyDisplay?: 'code' | 'symbol' | 'narrowSymbol' | 'name'notation?: 'standard' | 'scientific' | 'engineering' | 'compact'minimumFractionDigits?: numbermaximumFractionDigits?: number- And more...
License
MIT
