Skip to content

Universal currency formatter supporting all world currencies with flexible formatting options, multi-locale support, and comprehensive testing.

License

Notifications You must be signed in to change notification settings

NeaByteLab/Number-Currency

Repository files navigation

🌍 Number-Currency

npm version License: MIT TypeScript Node.js Test Coverage

Universal currency formatter supporting all world currencies with flexible formatting options

A powerful, lightweight TypeScript library for formatting numbers and currencies with support for multiple locales, custom separators, unit abbreviations, and number-to-words conversion.

✨ Features

  • 🌍 Multi-Currency Support: All world currencies with ISO 4217 codes
  • 🎨 Flexible Formatting: Custom separators, decimal places, and symbol positioning
  • 🌐 Internationalization: Support for multiple languages and locales
  • 🔢 Number Utilities: Unit abbreviations (k, m, b, t), decimal rounding
  • 📝 Word Conversion: Convert numbers to written words in multiple languages
  • Type Safety: Full TypeScript support with strict typing
  • 🚀 Performance: Optimized for speed and memory efficiency
  • 📱 Universal: Works in Node.js and modern browsers

🚀 Quick Start

Installation

npm install @neabyte/number-currency

Basic Usage

import { 
  formatCurrency, 
  formatNumber, 
  numberToWords,
  getCurrency,
  getAllCurrencies,
  getCurrencyName,
  getSupportedLocale,
  isSupportedLocale,
  getPluralForm,
  toUnitAbbreviation,
  roundToDecimal
} from '@neabyte/number-currency'

// Format USD currency
formatCurrency(1234.56, 'USD')
// Output: "$1,234.56"

// Format EUR currency (European style)
formatCurrency(1234.56, 'EUR')
// Output: "€1.234,56"

// Format with custom options
formatCurrency(1234.56, 'USD', {
  symbol: false,
  dot: '.',
  decimal: ',',
  floatingPoint: 3
})
// Output: "1.234,560"

// Number formatting with custom separators
formatNumber(1234567.89, ' ', ',', 3)
// Output: "1 234 567,890"

// Convert to words
numberToWords(1234)
// Output: "one thousand two hundred thirty four"

📚 API Reference

Core Functions

formatCurrency(amount, currencyCode, options?)

Formats a number as currency with the specified currency code.

formatCurrency(1234.56, 'USD')
// "$1,234.56"

formatCurrency(1234.56, 'EUR', { 
  symbol: false, 
  dot: '.', 
  decimal: ',' 
})
// "1.234,56"

Parameters:

  • amount (number): The amount to format
  • currencyCode (string): 3-letter ISO currency code (e.g., 'USD', 'EUR')
  • options (FormatOptions): Optional formatting configuration

FormatOptions:

interface FormatOptions {
  symbol?: string | boolean | null; // Currency symbol to display, or false to hide
  formal?: boolean;                 // Whether to use formal formatting
  dot?: string;                     // Custom thousand separator character
  decimal?: string;                 // Custom decimal separator character
  floatingPoint?: number;           // Number of decimal places to show
  replaceZeroDecimals?: boolean;    // Whether to remove trailing zeros after decimal
  useUnit?: boolean;                // Whether to include unit abbreviation
  k?: boolean;                      // Whether to use K/M/B abbreviations for large numbers
  longUnit?: boolean;               // Whether to use long unit names instead of abbreviations
  spaceBeforeUnit?: boolean;        // Whether to add space before unit
  locale?: string;                  // Locale for formatting rules
  style?: 'standard' | 'accounting' | 'financial'; // Formatting style for negative numbers
  convertToWords?: boolean;         // Whether to convert numbers to words
}

formatNumber(num, thousandSeparator?, decimalSeparator?, decimalPlaces?)

Formats a number with custom separators and decimal places.

formatNumber(1234567.89, ',', '.', 2)
// "1,234,567.89"

formatNumber(1234567.89, ' ', ',', 3)
// "1 234 567,890"

toUnitAbbreviation(num, useShort?)

Converts large numbers to abbreviated units.

toUnitAbbreviation(1500000)
// "1.5m"

toUnitAbbreviation(1500000, false)
// "1.5 million"

numberToWords(num, locale?)

Converts numbers to written words.

numberToWords(1234, 'en')
// "one thousand two hundred thirty four"

numberToWords(1000000, 'en')
// "one million"

Currency Database

getCurrency(currencyCode)

Retrieves currency information by code.

const usd = getCurrency('USD')
// {
//   code: 'USD',
//   name: 'US Dollar',
//   symbol: '$',
//   symbolPosition: 'before',
//   decimalPlaces: 2,
//   thousandSeparator: ',',
//   decimalSeparator: '.',
//   formal: false,
//   locale: 'en'
// }

getAllCurrencies()

Returns all supported currencies.

const currencies = getAllCurrencies()
// Array of all currency objects

getCurrencyName(currencyCode, locale)

Gets the localized name of a currency.

const name = getCurrencyName('USD', 'es')
// "dólar estadounidense"

getSupportedLocale(locale)

Gets a supported locale or defaults to English.

const locale = getSupportedLocale('en-US')
// "en"

isSupportedLocale(locale)

Checks if a locale is supported.

const supported = isSupportedLocale('fr')
// true

getPluralForm(currencyName, locale)

Gets the plural form of a currency name.

const plural = getPluralForm('dollar', 'en')
// "dollars"

roundToDecimal(num, decimalPlaces)

Rounds a number to specified decimal places.

const rounded = roundToDecimal(3.14159, 2)
// 3.14

Validation Functions

The library includes comprehensive validation functions:

import {
  validateNumber,
  validateString,
  validateBoolean,
  validateInteger,
  validateCurrencyCode,
  validateLocale,
  validateSeparator,
  validateSupportedLocale,
  validateAmount,
  validateNumberSize,
  validateDecimalPlaces
} from '@neabyte/number-currency'

// Example usage
validateCurrencyCode('USD')  // ✅ Valid
validateCurrencyCode('INVALID')  // ❌ Throws error
validateSeparator(' ', 'separator')  // ✅ Valid
validateSupportedLocale('en')  // ✅ Valid

**Note**: The library exports many more utility functions. See the full API reference above for complete details.

## 🌐 Supported Locales

- **English** (`en`) - Default
- **Spanish** (`es`)
- **French** (`fr`)
- **German** (`de`)
- **Japanese** (`ja`)

## 💱 Supported Currencies

The library supports all major world currencies including:

- **USD** - US Dollar
- **EUR** - Euro
- **JPY** - Japanese Yen
- **GBP** - British Pound
- **CNY** - Chinese Yuan
- **INR** - Indian Rupee
- **BRL** - Brazilian Real
- **KRW** - South Korean Won
- **CAD** - Canadian Dollar
- **AUD** - Australian Dollar
- And many more...

## 🛠️ Development

### Prerequisites

- Node.js >= 22.0.0
- npm or yarn

### Setup

```bash
# Clone the repository
git clone https://github.com/NeaByteLab/Number-Currency.git
cd Number-Currency

# Install dependencies
npm install

# Build the project
npm run build

# Run tests
npm test

# Run tests with coverage
npm run test:coverage

Available Scripts

  • npm run build - Build the project
  • npm run dev - Watch mode for development
  • npm test - Run tests in watch mode
  • npm run test:run - Run tests once
  • npm run test:coverage - Run tests with coverage
  • npm run lint - Run ESLint
  • npm run lint:fix - Fix ESLint issues
  • npm run format - Format code with Prettier
  • npm run type-check - TypeScript type checking

Project Structure

Number-Currency/
├── src/
│   ├── constants/         # Currency data and constants
│   ├── core/              # Core formatting logic
│   ├── interfaces/        # TypeScript type definitions
│   ├── utils/             # Utility functions
│   └── index.ts           # Main entry point
├── tests/                 # Test files
├── dist/                  # Built output
├── vitest.config.ts       # Test configuration
├── tsconfig.json          # TypeScript configuration
└── package.json           # Package configuration

📦 Browser Support

The library is compatible with:

  • Modern Browsers: Chrome 90+, Firefox 88+, Safari 14+, Edge 90+
  • ES Modules: Full ES2022+ support
  • Bundlers: Webpack, Vite, Rollup, Parcel
  • Frameworks: React, Vue, Angular, Svelte

Browser Usage

<script type="module">
  import { formatCurrency } from 'https://unpkg.com/@neabyte/number-currency@latest/dist/index.js'
  
  const result = formatCurrency(1234.56, 'USD')
  console.log(result) // "$1,234.56"
</script>

<!-- Alternative CDN (jsDelivr) -->
<script type="module">
  import { formatCurrency } from 'https://cdn.jsdelivr.net/npm/@neabyte/number-currency@latest/dist/index.js'
  
  const result = formatCurrency(1234.56, 'USD')
  console.log(result) // "$1,234.56"
</script>

🔧 Configuration

TypeScript

The library is built with TypeScript and includes full type definitions. No additional @types package is required.

Path Aliases

The project uses TypeScript path aliases for clean imports:

import { ... } from '@core/CurrencyFormatter'
import { ... } from '@utils/NumberUtils'
import { ... } from '@constants/Validation'
import type { ... } from '@interfaces/Currency'

🧪 Testing

The project includes comprehensive test coverage:

  • Test Framework: Vitest
  • Coverage: 99.62% overall coverage
  • Test Count: 127 test cases
  • Coverage Provider: v8

Run tests with:

npm test               # Watch mode
npm run test:run       # Single run
npm run test:coverage  # With coverage report

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

Contributing Guidelines

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.