Skip to content

API Reference ​

This page documents the complete API for ts-numbers.

Core Class: Numbers ​

The main class that provides all functionality.

Constructor ​

typescript
constructor(element: HTMLElement | string, config: NumbersConfig = {})

Creates a new Numbers instance.

  • element: An HTMLElement or CSS selector string referencing the input element to attach to
  • config: Configuration options (see Configuration Options)

Instance Methods ​

MethodDescription
set(value: number | string)Sets a new value with formatting applied
get()Gets the current value as a string
getNumber()Gets the current value as a number
getLocalized()Gets the localized value according to current configuration
getElement()Gets the DOM element that this instance is attached to
getConfig()Gets the current configuration
update(config: Partial<NumbersConfig>)Updates the configuration
clear()Clears the current value
remove()Removes the formatting and event listeners
setCurrency(currencyCode: string)Sets a specific currency format
getAvailableCurrencies()Returns an array of available currency codes
undo()Reverts to the previous value (if history enabled)
redo()Reverts an undo action (if history enabled)

All instance methods (except getNumber(), get(), getElement(), etc.) return the Numbers instance for chaining.

Configuration Options ​

Basic Formatting ​

OptionTypeDefaultDescription
decimalPlacesnumber2Number of decimal places to display
decimalCharacterstring'.'Character used for the decimal separator
decimalCharacterAlternativestring | nullnullAlternative decimal character (e.g., ',')
digitGroupSeparatorstring','Character used for thousands separator
digitGroupSpacingstring | number3Number of digits between separators

Currency Formatting ​

OptionTypeDefaultDescription
currencySymbolstring''Currency symbol to display
currencySymbolPlacement'p' | 's''p'Placement of currency symbol: prefix or suffix

Number Constraints ​

OptionTypeDefaultDescription
minimumValuestringundefinedMinimum allowed value
maximumValuestringundefinedMaximum allowed value
overrideMinMaxLimits'ceiling' | 'floor' | 'ignore' | 'invalid' | nullnullBehavior when value exceeds min/max limits

Decimal Behavior ​

OptionTypeDefaultDescription
allowDecimalPaddingboolean | 'floats'trueWhether to pad decimals with zeros
alwaysAllowDecimalCharacterbooleanfalseAlways allow decimal character (even if decimalPlaces: 0)

Display and Interaction ​

OptionTypeDefaultDescription
caretPositionOnFocus'start' | 'end' | 'decimalChar' | nullnullWhere to position cursor on focus
emptyInputBehaviorstring'focus'Behavior when input is empty
leadingZero'allow' | 'deny' | 'keep''deny'How to handle leading zeros
negativePositiveSignPlacement'l' | 'r' | 'p' | 's' | null'l'Position of negative/positive sign
negativeSignCharacterstring'-'Character for negative sign
positiveSignCharacterstring'+'Character for positive sign
showPositiveSignbooleanfalseWhether to show plus sign for positive numbers
suffixTextstring''Text to append after the number
negativeBracketsTypeOnBlurstring | nullnullBrackets for negative numbers, e.g., '(,)'

Interaction Options ​

OptionTypeDefaultDescription
selectOnFocusbooleanfalseSelect entire value on focus
selectNumberOnlybooleanfalseSelect only the numeric part on focus
readOnlybooleanfalseMake the input read-only
modifyValueOnWheelbooleanfalseAllow value change via mouse wheel
wheelStep'progressive' | string | number1Increment size for mouse wheel
modifyValueOnUpDownArrowbooleanfalseAllow value change via up/down arrow keys
upDownStep'progressive' | string | number1Increment size for arrow keys
wheelOn'focus' | 'hover''focus'When to apply wheel events

Scaling Options ​

OptionTypeDefaultDescription
divisorWhenUnfocusednumber | nullnullDivisor applied to value when not focused
decimalPlacesShownOnBlurnumber | nullnullDecimal places shown when element loses focus
decimalPlacesShownOnFocusnumber | nullnullDecimal places shown when element has focus
symbolWhenUnfocusedstring | nullnullSymbol to show when not focused

Specialized Types ​

OptionTypeDefaultDescription
isSpecializedTypestring | nullnullType of specialized formatting: 'phone', 'temperature', etc.
specializedOptionsobjectundefinedOptions for the specialized type

Scientific Notation ​

OptionTypeDefaultDescription
useScientificNotationbooleanfalseEnable scientific notation
scientificNotationThresholdnumber1e+15Threshold for using scientific notation
engineeringNotationbooleanfalseUse engineering notation (exponents in multiples of 3)

Internationalization ​

OptionTypeDefaultDescription
localestringundefinedLocale code (e.g., 'en-US', 'de-DE')
useGroupingbooleantrueWhether to use digit grouping (thousands separators)
numberingSystemstringundefinedNumbering system (e.g., 'arab', 'latn')

Miscellaneous ​

OptionTypeDefaultDescription
roundingMethodstring'S'Rounding method
saveValueToSessionStoragebooleanfalseSave value to sessionStorage
createLocalListbooleantrueAdd instance to global list
watchExternalChangesbooleanfalseWatch for external value changes
verbosebooleanfalseEnable verbose console logging

Static Functions ​

ts-numbers also provides standalone formatting functions:

typescript
// Format a number according to configuration
formatNumber({ value: number | string, config?: NumbersConfig }): string

// Parse a formatted string back to a number
parseNumber({ value: string, config?: NumbersConfig }): number

Presets ​

ts-numbers includes many predefined configuration presets:

typescript
import {
  arabicSA, // Currency presets
  dollar,
  euro,
  float, // Locale presets
  frenchFR,
  germanDE,

  hebrewIL, // Number format presets
  integer,
  ipv4,
  percentage,

  phoneInternational, // Specialized format presets
  phoneUS,
  pound,
  rupee,

  scientific,
  time24h,
  yen,
  yuan
} from 'ts-numbers/presets'

These can be imported and used directly with the Numbers constructor:

typescript
const dollarInput = new Numbers('#price', dollar)

Events ​

The following events are dispatched on the element:

EventDescription
numbers:formattedFired after formatting is applied
numbers:changeFired when the value changes
numbers:minExceededFired when input is below minimum allowed value
numbers:maxExceededFired when input exceeds maximum allowed value
numbers:invalidFired when invalid input is detected

Events include detail with relevant information:

typescript
element.addEventListener('numbers:change', (e) => {
  console.log('New value:', e.detail.value)
  console.log('Formatted value:', e.detail.formatted)
})