Introduction
Numeral.js is a JavaScript library for formatting and unformatting numbers. It handles currencies, percentages, byte sizes, ordinals, time durations, and custom patterns. It is inspired by Moment.js but focused on numbers rather than dates, providing a clean chainable API.
What Numeral.js Does
- Formats numbers as currencies, percentages, file sizes, and custom patterns
- Parses formatted strings back into numeric values
- Supports locale-aware formatting for international number conventions
- Handles abbreviations (1K, 1M, 1B) and ordinal suffixes (1st, 2nd, 3rd)
- Provides arithmetic methods (add, subtract, multiply, divide) on wrapped values
Architecture Overview
Numeral.js wraps a numeric value in a Numeral object that exposes formatting and manipulation methods. Locales are registered as plugins defining delimiters, currency symbols, and abbreviations. Format strings are parsed character by character using a pattern-matching system that maps tokens like 0, #, and $ to output segments.
Self-Hosting & Configuration
- Install via npm or include the script tag from a CDN
- Register locales with
numeral.register('locale', ...)for international formatting - Set the active locale with
numeral.locale('fr')for French conventions - Create custom format patterns by registering new format functions
- Zero dependencies; works in Node.js and all browsers including IE11
Key Features
- Compact format string syntax ('0,0.00', '$0.0a', '0b') for common patterns
- Built-in byte formatting for file sizes (KB, MB, GB, TB)
- Unformat capability to parse localized strings back to numbers
- Pluggable locale system with community-contributed language packs
- Tiny footprint at around 11 KB minified
Comparison with Similar Tools
- Intl.NumberFormat — Native browser API; no dependency but less ergonomic for complex patterns
- accounting.js — Similar focus but unmaintained; Numeral.js has broader format support
- d3-format — Part of D3 ecosystem; uses C-style format specifiers instead of pattern strings
- currency.js — Specialized for currency math; Numeral.js handles more format types
FAQ
Q: Is Numeral.js still maintained? A: Active development has slowed, but the library remains widely used and stable.
Q: How does it compare to Intl.NumberFormat? A: Intl.NumberFormat is native but verbose; Numeral.js provides a more concise pattern-based API.
Q: Can I use it in TypeScript? A: Yes, type definitions are available via @types/numeral.
Q: Does it handle BigInt or arbitrary precision? A: No, it works with standard JavaScript numbers (IEEE 754 doubles).