### Install n2words
Source: https://github.com/forzagreen/n2words/blob/main/README.md
Install the n2words package using npm.
```bash
npm install n2words
```
--------------------------------
### Clone Repository and Install Dependencies
Source: https://github.com/forzagreen/n2words/blob/main/CONTRIBUTING.md
Clone the n2words repository, navigate into the directory, install npm dependencies, and run tests to quickly set up the project for development.
```bash
git clone https://github.com/YOUR_USERNAME/n2words.git
cd n2words
npm install
npm test
```
--------------------------------
### CardinalOptions Example Usage
Source: https://github.com/forzagreen/n2words/blob/main/_autodocs/types.md
Provides examples of using `toCardinal` with language-specific options for English (en-US) and French, demonstrating 'and', 'hundredPairing', and 'gender' options.
```typescript
// en-US
toCardinal(42, { and: true, hundredPairing: false })
// French
toCardinal(42, { gender: 'feminine' })
```
--------------------------------
### Document Supported Options for Languages
Source: https://github.com/forzagreen/n2words/blob/main/_autodocs/configuration.md
An example demonstrating how to document and retrieve supported options for a given language and conversion form.
```javascript
const LANGUAGE_OPTIONS = {
'en-US': {
toCardinal: ['and', 'hundredPairing'],
toCurrency: ['and']
},
'es-ES': {
toCardinal: ['gender'],
toCurrency: ['gender', 'currency']
},
'ja-JP': {
toCardinal: [],
toCurrency: []
}
}
function getAvailableOptions(language, form) {
return LANGUAGE_OPTIONS[language]?.[form] ?? []
}
```
--------------------------------
### ScaleMax Example Usage
Source: https://github.com/forzagreen/n2words/blob/main/_autodocs/types.md
Illustrates the usage of `ScaleMax` with examples for a bounded cardinal form in en-US and an unbounded form in fa-IR (Persian).
```typescript
export const cardinalMax: ScaleMax = 10n ** 63n // en-US
export const cardinalMax: ScaleMax = null // fa-IR (Persian, unbounded)
```
--------------------------------
### Input Sanitization Example
Source: https://github.com/forzagreen/n2words/blob/main/_autodocs/errors.md
Demonstrates cleaning user input by trimming whitespace before passing it to the toCardinal function.
```javascript
// Clean user input before conversion
function cleanInput(value) {
if (typeof value === 'string') {
return value.trim() // Remove whitespace
}
return value
}
const cleaned = cleanInput(userInput)
const words = toCardinal(cleaned)
```
--------------------------------
### Language Module Import Examples
Source: https://github.com/forzagreen/n2words/blob/main/_autodocs/types.md
Demonstrates how to import functions and constants from different language modules. Note that not all languages may export all forms.
```typescript
// en-US module
import { toCardinal, toOrdinal, toCurrency, cardinalMax, ordinalMax, currencyMax } from 'n2words/en-US'
// ja-JP module
import { toCardinal, toOrdinal, toCurrency, cardinalMax, ordinalMax, currencyMax } from 'n2words/ja-JP'
// Some languages may not have all forms
import { toCardinal } from 'n2words/some-language'
```
--------------------------------
### CurrencyOptions Example Usage
Source: https://github.com/forzagreen/n2words/blob/main/_autodocs/types.md
Demonstrates using `toCurrency` with language-specific options for English (en-US) and French, showing the 'and' option and default currency usage.
```typescript
// en-US
toCurrency(42.50, { and: true })
// French
toCurrency(42.50) // Uses euros
```
--------------------------------
### Conventional Commit: Performance
Source: https://github.com/forzagreen/n2words/blob/main/CLAUDE.md
Example of a conventional commit for performance improvements, specifying the scope (language) and a brief description.
```bash
perf(ja-JP): optimize BigInt handling
```
--------------------------------
### TypeError Example Messages
Source: https://github.com/forzagreen/n2words/blob/main/_autodocs/types.md
Provides example error messages for `TypeError`, indicating invalid input types or incorrect options format.
```text
"Invalid value type: expected number, string, or bigint, received object"
"Invalid options: expected plain object or undefined, got array"
```
--------------------------------
### Usage of v2 converter (Node.js)
Source: https://github.com/forzagreen/n2words/blob/main/CHANGELOG.md
v2 used class instantiation for conversions. This example shows using the EnglishConverter.
```javascript
EnglishConverter(42)
```
--------------------------------
### isPlainObject Examples
Source: https://github.com/forzagreen/n2words/blob/main/_autodocs/utilities.md
Demonstrates the usage of `isPlainObject` with various data types to show true and false return values. Ensure the utility is imported before use.
```javascript
import { isPlainObject } from 'n2words/utils/is-plain-object.js'
isPlainObject({})
isPlainObject({ a: 1, b: 2 })
isPlainObject(Object.create(null))
isPlainObject(null)
isPlainObject([])
isPlainObject([1, 2, 3])
isPlainObject('string')
isPlainObject(42)
isPlainObject(new Map())
isPlainObject(new Set())
isPlainObject(class Foo {})
isPlainObject(new (class Foo {})())
```
--------------------------------
### Yoruba toCardinal Example
Source: https://github.com/forzagreen/n2words/blob/main/_autodocs/configuration.md
Shows the toCardinal function for Yoruba, converting a number to its word representation.
```javascript
import { toCardinal } from 'n2words/yo-NG'
toCardinal(42) // 'àlààdó-ojì'
```
--------------------------------
### Swedish toCardinal Example
Source: https://github.com/forzagreen/n2words/blob/main/_autodocs/configuration.md
Illustrates the toCardinal function for Swedish, showing conversion of numbers.
```javascript
import { toCardinal } from 'n2words/sv-SE'
toCardinal(42) // 'fyrtiotvå'
toCardinal(1234) // 'etttusentvåhundratrettiofyra'
```
--------------------------------
### Conventional Commit: Feature
Source: https://github.com/forzagreen/n2words/blob/main/CLAUDE.md
Example of a conventional commit for adding a new feature, specifying the scope (language) and a brief description.
```bash
feat(pt-BR): add Brazilian Portuguese
```
--------------------------------
### ESM Import Examples
Source: https://github.com/forzagreen/n2words/blob/main/README.md
Illustrates how to import functions from n2words using ECMAScript Modules (ESM) syntax for single or multiple forms, and aliased imports.
```javascript
import { toCardinal } from 'n2words/en-US' // Single form
import { toCardinal, toOrdinal } from 'n2words/en-US' // Multiple forms
import { toCardinal as fr } from 'n2words/fr-FR' // Aliased import
```
--------------------------------
### OrdinalParseResult Example
Source: https://github.com/forzagreen/n2words/blob/main/_autodocs/types.md
Shows an example of parsing a numeric string into an ordinal BigInt using `parseOrdinalValue`.
```typescript
parseOrdinalValue('42')
// 42n
```
--------------------------------
### Dutch toCardinal Example
Source: https://github.com/forzagreen/n2words/blob/main/_autodocs/configuration.md
Shows the toCardinal function for Dutch, converting numbers to words.
```javascript
import { toCardinal } from 'n2words/nl-NL'
toCardinal(42) // 'tweeënveertig'
toCardinal(1234) // 'duizendtweehonderdvierendertig'
```
--------------------------------
### ESM Import Example
Source: https://github.com/forzagreen/n2words/blob/main/_autodocs/types.md
Illustrates the correct way to import from n2words using ECMAScript Modules (ESM). The library is ESM-only in its source form.
```typescript
// ESM (only way to import)
import { toCardinal, toOrdinal, toCurrency } from 'n2words/en-US'
```
--------------------------------
### Hausa toCardinal Example
Source: https://github.com/forzagreen/n2words/blob/main/_autodocs/configuration.md
Illustrates the toCardinal function for Hausa, converting a number to its word representation.
```javascript
import { toCardinal } from 'n2words/ha-NG'
toCardinal(42) // 'bà dà dù'
```
--------------------------------
### Importing multiple languages in v3
Source: https://github.com/forzagreen/n2words/blob/main/CHANGELOG.md
In v3, explicit language imports are required for tree-shaking. This example shows how to import multiple languages.
```javascript
import { en, es } from 'n2words'
```
--------------------------------
### CurrencyParseResult Example
Source: https://github.com/forzagreen/n2words/blob/main/_autodocs/types.md
Illustrates the output of `parseCurrencyValue` for negative and positive currency inputs, highlighting the truncation of cents.
```typescript
parseCurrencyValue(-42.996)
// { isNegative: true, dollars: 42n, cents: 99n } // 99, not 100 (truncated)
parseCurrencyValue(0.50)
// { isNegative: false, dollars: 0n, cents: 50n }
```
--------------------------------
### Conventional Commit: Fix
Source: https://github.com/forzagreen/n2words/blob/main/CLAUDE.md
Example of a conventional commit for fixing an issue, specifying the scope (language) and a brief description.
```bash
fix(en-US): correct thousand handling
```
--------------------------------
### Scientific Notation Expansion Examples
Source: https://github.com/forzagreen/n2words/blob/main/_autodocs/types.md
Illustrates how n2words automatically expands scientific notation in string inputs during parsing. This process is transparent to the user.
```typescript
type ScientificNotation = `${number}e${number}` | `${number}E${number}`
// Examples that are automatically expanded:
'1e6' → '1000000'
'1.5e3' → '1500'
'1e-3' → '0.001'
'1.23e2' → '123'
'-1.5e-4' → '-0.00015'
```
--------------------------------
### Browser Usage with CDN (ESM)
Source: https://github.com/forzagreen/n2words/blob/main/README.md
Example of using n2words in a browser via a CDN using the recommended ESM import method.
```html
```
--------------------------------
### CardinalParseResult Example
Source: https://github.com/forzagreen/n2words/blob/main/_autodocs/types.md
Demonstrates the output structure of `parseCardinalValue` for negative and positive numbers, showing how integer and decimal parts are represented.
```typescript
parseCardinalValue(-42.50)
// { isNegative: true, integerPart: 42n, decimalPart: '50' }
parseCardinalValue(123)
// { isNegative: false, integerPart: 123n }
```
--------------------------------
### Importing a single language converter in v2
Source: https://github.com/forzagreen/n2words/blob/main/CHANGELOG.md
In v2, specific language converters were imported from language-specific modules. This example shows importing the English converter.
```javascript
import { EnglishConverter } from 'n2words/en'
```
--------------------------------
### Usage of v1 converter (default export)
Source: https://github.com/forzagreen/n2words/blob/main/CHANGELOG.md
v1 used a configuration object with a 'lang' property for language selection. This example shows converting the number 42 to Spanish.
```javascript
n2words(42, { lang: 'es' })
```
--------------------------------
### Usage of v2 converter (Browser)
Source: https://github.com/forzagreen/n2words/blob/main/CHANGELOG.md
In a browser, v2 converters were accessed as properties of the n2words object. This example shows using the EnglishConverter.
```javascript
n2words.EnglishConverter(42)
```
--------------------------------
### Conventional Commit: Multiple Fixes
Source: https://github.com/forzagreen/n2words/blob/main/CLAUDE.md
Example of a conventional commit for fixing issues in multiple languages, specifying a comma-separated scope and a brief description.
```bash
fix(az-AZ,tr-TR): guard scale ceilings
```
--------------------------------
### Importing a single language in v3
Source: https://github.com/forzagreen/n2words/blob/main/CHANGELOG.md
For tree-shaking, import specific languages using their subpath exports. This example shows importing the 'es' language.
```javascript
import { toWords } from 'n2words/es'
```
--------------------------------
### TypeError Examples for Invalid Input
Source: https://github.com/forzagreen/n2words/blob/main/_autodocs/errors.md
Demonstrates TypeErrors when providing invalid input types or options to n2words parsing functions.
```javascript
import { toCardinal } from 'n2words/en-US'
// TypeError: invalid value type
toCardinal([]) // TypeError: expected number, string, or bigint
toCardinal({}) // TypeError: expected number, string, or bigint
toCardinal(undefined) // TypeError: expected number, string, or bigint
// TypeError: invalid options
toCardinal(42, 'options') // TypeError: expected plain object or undefined
toCardinal(42, null) // TypeError: expected plain object or undefined
toCardinal(42, []) // TypeError: expected plain object or undefined
toCardinal(42, new Map()) // TypeError: expected plain object or undefined
```
--------------------------------
### Import Paths for n2words
Source: https://github.com/forzagreen/n2words/blob/main/LANGUAGES.md
Import paths for n2words use BCP 47 language codes. Examples include 'n2words/en-US', 'n2words/zh-Hans-CN', and 'n2words/fr-BE'.
```javascript
import "n2words/en-US";
import "n2words/zh-Hans-CN";
import "n2words/fr-BE";
```
--------------------------------
### Browser Usage with CDN (UMD)
Source: https://github.com/forzagreen/n2words/blob/main/README.md
Example of using n2words in a browser via a CDN using the legacy UMD script tag method.
```html
```
--------------------------------
### Usage of imported language in v3 (Node.js)
Source: https://github.com/forzagreen/n2words/blob/main/CHANGELOG.md
After importing a language, you can use the exported function directly. This example shows using the 'es' language.
```javascript
es(42)
```
--------------------------------
### RangeError Examples for Out-of-Range Values
Source: https://github.com/forzagreen/n2words/blob/main/_autodocs/errors.md
Illustrates RangeErrors for non-finite numbers, invalid ordinal values, incorrect string formats, and values exceeding the supported maximum.
```javascript
import { toCardinal, toOrdinal, toCurrency } from 'n2words/en-US'
// RangeError: non-finite numbers (cardinal/currency)
toCardinal(NaN) // RangeError: not finite
toCardinal(Infinity) // RangeError: not finite
toCurrency(NaN) // RangeError: not finite
// RangeError: invalid ordinal values
toOrdinal(0) // RangeError: must be positive
toOrdinal(-42) // RangeError: must be positive
toOrdinal(42.5) // RangeError: must be whole number
toOrdinal('42.5') // RangeError: must be whole number
toOrdinal('1e-3') // RangeError: must be whole number (expansion = 0.001)
// RangeError: invalid string formats
toCardinal('') // RangeError: invalid format
toCardinal('not a number') // RangeError: invalid format
toCardinal(' ') // RangeError: invalid format
// RangeError: exceeds form maximum
toCardinal('9' + '0'.repeat(63)) // RangeError: value too large (en-US max is 10^63-1)
toOrdinal(10n ** 63n) // RangeError: value too large
```
--------------------------------
### Import Language Module
Source: https://github.com/forzagreen/n2words/blob/main/_autodocs/api-reference/language-overview.md
Demonstrates the standard import pattern for any language module. Replace `{language-code}` with the appropriate IETF BCP 47 tag.
```javascript
import { toCardinal, toOrdinal, toCurrency } from 'n2words/{language-code}'
```
--------------------------------
### Run Benchmarks for All Languages
Source: https://github.com/forzagreen/n2words/blob/main/CLAUDE.md
Executes performance benchmarks for all implemented languages.
```bash
npm run bench # All languages
```
--------------------------------
### Run Benchmarks for Multiple Languages
Source: https://github.com/forzagreen/n2words/blob/main/CLAUDE.md
Executes performance benchmarks for a comma-separated list of languages.
```bash
npm run bench -- en-US,fr-FR,de-DE # Multiple languages
```
--------------------------------
### Add New Language Stub
Source: https://github.com/forzagreen/n2words/blob/main/CLAUDE.md
Use this command to create the initial stub, fixture, and type tests for a new language.
```bash
npm run lang:add -- # Creates stub + fixture + type tests
```
--------------------------------
### Create Feature Branch and Commit Changes
Source: https://github.com/forzagreen/n2words/blob/main/CONTRIBUTING.md
Create a new branch for your feature, make code changes, and then lint and test your code before committing. Use Conventional Commits for commit messages.
```bash
git checkout -b feat/add-pt-BR
npm run lint && npm test
git commit -m "feat(ko-KR): add Korean"
```
--------------------------------
### Run Tests with Coverage Report
Source: https://github.com/forzagreen/n2words/blob/main/CONTRIBUTING.md
Execute unit tests and generate a code coverage report. This helps in identifying parts of the codebase that are not adequately tested.
```bash
npm run coverage
```
--------------------------------
### Import Patterns
Source: https://github.com/forzagreen/n2words/blob/main/_autodocs/api-reference/en-US.md
Demonstrates various ways to import functions and constants from the n2words library using ESM syntax.
```APIDOC
## Import Patterns
### ESM (Node.js ≥22, modern bundlers)
```javascript
// Single form
import { toCardinal } from 'n2words/en-US'
// Multiple forms
import { toCardinal, toOrdinal, toCurrency } from 'n2words/en-US'
// Aliased import
import { toCardinal as englishToCardinal } from 'n2words/en-US'
```
```
--------------------------------
### Run Unit Tests and Build Types
Source: https://github.com/forzagreen/n2words/blob/main/CONTRIBUTING.md
Execute the project's unit tests and build TypeScript type definitions. This is a standard command for verifying code integrity and ensuring type safety.
```bash
npm test
```
--------------------------------
### Basic Usage
Source: https://github.com/forzagreen/n2words/blob/main/_autodocs/README.md
Demonstrates how to import and use the primary functions `toCardinal`, `toOrdinal`, and `toCurrency` from the n2words library for a specified language.
```APIDOC
## Basic Usage
### Description
This section shows the fundamental way to use the n2words library. It covers importing the core conversion functions (`toCardinal`, `toOrdinal`, `toCurrency`) for a specific language and provides examples of their output.
### Import
```javascript
import { toCardinal, toOrdinal, toCurrency } from 'n2words/{language-code}'
```
### Usage Examples
- **Cardinal Numbers**: Converts a number to its word representation (e.g., 42 to "forty-two").
```javascript
toCardinal(42)
```
- **Ordinal Numbers**: Converts a number to its word representation in ordinal form (e.g., 42 to "forty-second").
```javascript
toOrdinal(42)
```
- **Currency**: Converts a monetary value to its word representation (e.g., 42.50 to "forty-two dollars and fifty cents").
```javascript
toCurrency(42.50)
```
### Parameters
- **value**: `number | string | bigint` - The number to convert.
- **options**: `Record` - Optional configuration object for specific language behaviors (used with `toCardinal` and `toCurrency`).
### Response
- **string**: The word representation of the input number.
```
--------------------------------
### Importing Language Modules in n2words
Source: https://github.com/forzagreen/n2words/blob/main/LANGUAGES.md
Demonstrates how to import specific language modules for cardinal, ordinal, and currency conversion. Ensure the correct language code is used for import.
```javascript
import { toCardinal } from 'n2words/en-US'
```
```javascript
import { toCardinal, toOrdinal, toCurrency } from 'n2words/en-US'
```
```javascript
toCardinal(42) // 'forty-two'
toOrdinal(42) // 'forty-second' (if supported)
toCurrency(42.50) // 'forty-two dollars and fifty cents' (if supported)
```
--------------------------------
### Using toCardinal with Formal Option in Thai
Source: https://github.com/forzagreen/n2words/blob/main/_autodocs/api-reference/languages-with-options.md
Demonstrates how to use the `toCardinal` function with the `formal` option for Thai language. The formal option can alter the output style for numbers.
```javascript
import { toCardinal } from 'n2words/th-TH'
toCardinal(42)
// 'สี่สิบสอง'
toCardinal(42, { formal: true })
// 'สี่สิบสอง' (formal variant)
```
--------------------------------
### Run Benchmarks for a Single Language
Source: https://github.com/forzagreen/n2words/blob/main/CLAUDE.md
Executes performance benchmarks for a specified single language.
```bash
npm run bench -- en-US # Single language
```
--------------------------------
### Checking Language Support for Options
Source: https://github.com/forzagreen/n2words/blob/main/_autodocs/api-reference/languages-with-options.md
Provides a utility function to determine which options are supported for a given language and conversion form. This helps in understanding the available configurations.
```javascript
const SUPPORTED_OPTIONS = {
'en-US': { toCardinal: ['and', 'hundredPairing'], toCurrency: ['and'] },
'ru-RU': { toCardinal: ['gender', 'animate'], toCurrency: ['gender'] },
'es-ES': { toCardinal: ['gender'], toCurrency: ['gender', 'currency'] },
}
function getLanguageOptions(language, form) {
return SUPPORTED_OPTIONS[language]?.[form] ?? []
}
```
--------------------------------
### Module Import Pattern
Source: https://github.com/forzagreen/n2words/blob/main/_autodocs/api-reference/language-overview.md
Demonstrates the standard pattern for importing conversion functions from any language module in n2words. Replace `{language-code}` with the appropriate IETF BCP 47 tag.
```APIDOC
## Module Import Pattern
All language modules follow the same import pattern:
```javascript
import { toCardinal, toOrdinal, toCurrency } from 'n2words/{language-code}'
```
Where `{language-code}` is an IETF BCP 47 language tag (e.g., `en-US`, `zh-Hans-CN`, `fr-BE`).
```
--------------------------------
### American English (en-US) Currency Option: and
Source: https://github.com/forzagreen/n2words/blob/main/LANGUAGES.md
Use 'and' between dollars and cents in American English currency. For example, 'one dollar and fifty cents'.
```javascript
toCurrency(value, { and: true })
```
--------------------------------
### UMD Bundle Usage in HTML
Source: https://github.com/forzagreen/n2words/blob/main/_autodocs/types.md
Shows how to use the compiled UMD bundles of n2words in legacy browser environments via a script tag. Global namespace exposes converters.
```html
```
--------------------------------
### Options Pattern for toCardinal
Source: https://github.com/forzagreen/n2words/blob/main/CLAUDE.md
Demonstrates how to handle optional parameters, such as gender, in the `toCardinal` function using validation and destructuring.
```javascript
import { validateOptions } from './utils/validate-options.js'
/**
* @param {number | string | bigint} value
* @param {Object} [options]
* @param {('masculine'|'feminine')} [options.gender='masculine']
* @returns {string}
*/
function toCardinal (value, options) {
options = validateOptions(options)
const { isNegative, integerPart, decimalPart } = parseCardinalValue(value)
const { gender = 'masculine' } = options
// Pass explicit values to internal functions, not options object
}
```
--------------------------------
### Basic Usage of n2words Functions
Source: https://github.com/forzagreen/n2words/blob/main/_autodocs/README.md
Demonstrates the basic import and usage of toCardinal, toOrdinal, and toCurrency functions for number-to-word conversion.
```javascript
import { toCardinal, toOrdinal, toCurrency } from 'n2words/{language-code}'
// Cardinal: 42 → "forty-two"
toCardinal(42)
// Ordinal: 42 → "forty-second"
toOrdinal(42)
// Currency: 42.50 → "forty-two dollars and fifty cents"
toCurrency(42.50)
```
--------------------------------
### American English (en-US) Cardinal Option: and
Source: https://github.com/forzagreen/n2words/blob/main/LANGUAGES.md
Use 'and' after hundreds and before small numbers in American English cardinal numbers. For example, 'one hundred and one'.
```javascript
toCardinal(value, { and: true })
```
--------------------------------
### Usage of imported language in v3 (Browser)
Source: https://github.com/forzagreen/n2words/blob/main/CHANGELOG.md
In a browser environment, imported languages are accessed as properties of the main n2words object. This example shows using the 'es' language.
```javascript
n2words.es(42)
```
--------------------------------
### Dutch (Netherlands) nl-NL Cardinal Option: noHundredPairing
Source: https://github.com/forzagreen/n2words/blob/main/LANGUAGES.md
Disable hundred pairing in Dutch (Netherlands) cardinal numbers. For example, 1104 becomes 'duizend honderdvier' instead of using pairing.
```javascript
toCardinal(value, { noHundredPairing: true })
```
--------------------------------
### Importing all languages in v1
Source: https://github.com/forzagreen/n2words/blob/main/CHANGELOG.md
v1 bundled all languages into a single wrapper function with runtime language selection. This shows the default import.
```javascript
import n2words from 'n2words'
```
--------------------------------
### Import n2words Functions
Source: https://github.com/forzagreen/n2words/blob/main/_autodocs/configuration.md
Import the `toCardinal` and `toCurrency` functions from a specific language module. Options are passed as the second parameter.
```javascript
import { toCardinal, toCurrency } from 'n2words/{language}'
toCardinal(value, options?)
toCurrency(value, options?)
```
--------------------------------
### Language-Specific Default Options
Source: https://github.com/forzagreen/n2words/blob/main/_autodocs/README.md
Shows how to apply default conversion options based on the language, merging them with user-provided options for flexible number-to-words formatting.
```javascript
const defaultOptions = {
'en-US': { and: false, hundredPairing: false },
'es-ES': { gender: 'masculine' },
'ru-RU': { gender: 'masculine', animate: false },
'zh-Hans-CN': { formal: false },
// ... etc
}
function convertWithDefaults(value, language, userOptions = {}) {
const options = { ...defaultOptions[language], ...userOptions }
const module = await import(`n2words/${language}`)
return module.toCardinal(value, options)
}
```
--------------------------------
### Add a New Language
Source: https://github.com/forzagreen/n2words/blob/main/README.md
Use this command to scaffold a new language. Requires a BCP 47 language code.
```bash
npm run lang:add --
```
--------------------------------
### English Number to Words Conversion
Source: https://github.com/forzagreen/n2words/blob/main/_autodocs/README.md
Demonstrates basic and option-based conversion of numbers to cardinal and currency strings in English variants. Shows usage of 'and' conjunction and 'hundredPairing' option.
```javascript
import { toCardinal, toOrdinal, toCurrency } from 'n2words/en-US'
toCardinal(42) // 'forty-two'
toCardinal(42, { and: true }) // 'forty-two' (no change at this level)
toCardinal(101, { and: true }) // 'one hundred and one'
toCardinal(1500, { hundredPairing: true }) // 'fifteen hundred' (en-US only)
toCurrency(42.50) // 'forty-two dollars and fifty cents'
toCurrency(42.50, { and: false }) // 'forty-two dollars fifty cents'
```
--------------------------------
### Add a New Language
Source: https://github.com/forzagreen/n2words/blob/main/CONTRIBUTING.md
Use the provided npm script to scaffold the necessary files for a new language. This command requires a BCP 47 language code as an argument.
```bash
npm run lang:add -- # e.g., ko-KR, sr-Cyrl-RS, fr-BE
```
--------------------------------
### Run Performance Benchmarks
Source: https://github.com/forzagreen/n2words/blob/main/CONTRIBUTING.md
Execute performance benchmarks to measure the efficiency of different parts of the n2words library. This is useful for identifying performance regressions.
```bash
npm run bench
```
--------------------------------
### Import Patterns
Source: https://github.com/forzagreen/n2words/blob/main/_autodocs/README.md
Explains the different ways to import functions from the n2words library, including single and multiple function imports, and aliased imports, using language codes.
```APIDOC
## Import Patterns
### Description
This section details how to import the n2words library functions. It covers the use of IETF BCP 47 language codes and demonstrates various import syntaxes, including importing single or multiple functions and using aliases.
### Language Codes
Language codes follow the IETF BCP 47 standard (e.g., `en-US`, `zh-Hans-CN`, `fr-BE`).
### Import Examples
- **Single Function Import**: Imports only the `toCardinal` function for a specific language.
```javascript
import { toCardinal } from 'n2words/en-US'
```
- **Multiple Function Import**: Imports multiple functions (`toCardinal`, `toOrdinal`, `toCurrency`) for a specific language.
```javascript
import { toCardinal, toOrdinal, toCurrency } from 'n2words/en-US'
```
- **Aliased Import**: Imports a function with a custom alias for clarity or to avoid naming conflicts.
```javascript
import { toCardinal as englishCardinal } from 'n2words/en-US'
```
```
--------------------------------
### Biblical Hebrew toCardinal with Formal Option
Source: https://github.com/forzagreen/n2words/blob/main/_autodocs/configuration.md
Convert numbers to words using formal/biblical style in Hebrew (hbo-IL). Requires importing with an alias.
```javascript
import { toCardinal as biblicalCardinal } from 'n2words/hbo-IL'
biblicalCardinal(21, { formal: true }) // Biblical form
```
--------------------------------
### Browser Usage with ESM
Source: https://github.com/forzagreen/n2words/blob/main/_autodocs/api-reference/en-US.md
Import and use cardinal, ordinal, and currency conversion functions directly from the CDN using ES Modules.
```html
```
--------------------------------
### Basic Usage with Multiple Languages
Source: https://github.com/forzagreen/n2words/blob/main/README.md
Import and use the toCardinal function from different language modules. Aliasing is used for convenience.
```javascript
import { toCardinal } from 'n2words/en-US'
import { toCardinal as es } from 'n2words/es-ES'
toCardinal(42) // 'forty-two'
es(42) // 'cuarenta y dos'
```
--------------------------------
### Chinese Formal and Simplified Characters
Source: https://github.com/forzagreen/n2words/blob/main/_autodocs/README.md
Illustrates converting numbers to words in Chinese, showing the difference between simplified and formal character styles.
```javascript
import { toCardinal } from 'n2words/zh-Hans-CN'
toCardinal(42) // '四十二' (simplified)
toCardinal(42, { formal: true }) // '肆拾贰' (formal)
```
--------------------------------
### Error Context Preservation in Applications
Source: https://github.com/forzagreen/n2words/blob/main/_autodocs/errors.md
Demonstrates how to catch conversion errors, log detailed context including error type and input values, and provide user-friendly fallback messages for specific error types like RangeError.
```javascript
function convertNumberForDisplay(num, language) {
try {
const { toCardinal } = await import(`n2words/${language}`)
return toCardinal(num)
} catch (err) {
const context = {
error: err.message,
type: err.name,
number: num,
language: language,
timestamp: new Date().toISOString()
}
logger.error('Conversion failed', context)
if (err instanceof RangeError) {
return `[Unable to convert ${num} in ${language}]`
}
throw err
}
}
```
--------------------------------
### Providing Type-Safe Options with TypeScript
Source: https://github.com/forzagreen/n2words/blob/main/_autodocs/api-reference/languages-with-options.md
Illustrates how to use TypeScript interfaces to ensure type safety when passing options to conversion functions. This prevents runtime errors due to incorrect option types or values.
```typescript
interface LanguageOptions {
'en-US': {
toCardinal: { and?: boolean, hundredPairing?: boolean }
toCurrency: { and?: boolean }
}
'ru-RU': {
toCardinal: { gender?: 'masculine' | 'feminine' | 'neuter', animate?: boolean }
toCurrency: { gender?: 'masculine' | 'feminine' | 'neuter' }
}
// ... other languages
}
function convert(
lang: L,
form: 'toCardinal' | 'toCurrency',
value: number,
options?: LanguageOptions[L][form]
) {
// Type-safe conversion
}
```
--------------------------------
### Debugging n2words Errors with Try-Catch
Source: https://github.com/forzagreen/n2words/blob/main/_autodocs/errors.md
Illustrates how to use a try-catch block to handle errors thrown by n2words functions and access error details like name, message, and stack trace.
```javascript
try {
toCardinal('not a number')
} catch (err) {
console.error(err.name) // 'RangeError'
console.error(err.message) // 'Invalid number format: "not a number"'
console.error(err.stack) // Full stack trace with file/line info
}
```
--------------------------------
### Base CurrencyOptions Interface
Source: https://github.com/forzagreen/n2words/blob/main/_autodocs/types.md
Defines the base structure for currency conversion options, allowing for language-specific properties. Common options like 'and' and 'currency' are illustrated.
```typescript
interface CurrencyOptions {
[key: string]: unknown
}
```
--------------------------------
### Import Patterns for n2words
Source: https://github.com/forzagreen/n2words/blob/main/_autodocs/README.md
Shows different ways to import functions from n2words, including single forms, multiple forms, and aliased imports, using language codes.
```javascript
// Single form
import { toCardinal } from 'n2words/en-US'
// Multiple forms
import { toCardinal, toOrdinal, toCurrency } from 'n2words/en-US'
// Aliased import
import { toCardinal as englishCardinal } from 'n2words/en-US'
```
--------------------------------
### Run Extended Benchmarks
Source: https://github.com/forzagreen/n2words/blob/main/CLAUDE.md
Executes performance benchmarks with a longer run, increasing the number of iterations.
```bash
npm run bench -- en-US --full # Longer run (more iterations)
```
--------------------------------
### Locale-Aware Number Conversion
Source: https://github.com/forzagreen/n2words/blob/main/_autodocs/README.md
Demonstrates how to perform number-to-words conversion based on a given locale by mapping locales to language codes and dynamically importing the appropriate module.
```javascript
const localeToLanguage = {
'en-US': 'en-US',
'en-GB': 'en-GB',
'fr-FR': 'fr-FR',
'de-DE': 'de-DE',
'es-ES': 'es-ES',
'ja-JP': 'ja-JP',
// ... etc
}
function convertForLocale(value, locale) {
const language = localeToLanguage[locale]
const module = await import(`n2words/${language}`)
return module.toCardinal(value)
}
```
--------------------------------
### Provide Option Defaults for Conversion
Source: https://github.com/forzagreen/n2words/blob/main/_autodocs/configuration.md
A function that merges user-provided options with a set of default options for number conversion.
```javascript
function convertWithDefaults(value, language, userOptions = {}) {
const defaults = {
and: false,
gender: 'masculine',
currency: 'EUR'
}
const options = { ...defaults, ...userOptions }
const { toCardinal } = await import(`n2words/${language}`)
return toCardinal(value, options)
}
```
--------------------------------
### Importing Language Forms
Source: https://github.com/forzagreen/n2words/blob/main/CLAUDE.md
Import specific number-to-words conversion functions for a given language code.
```javascript
import { toCardinal, toOrdinal, toCurrency } from 'n2words/en-US'
```
--------------------------------
### Thai toCardinal Informal and Formal
Source: https://github.com/forzagreen/n2words/blob/main/_autodocs/configuration.md
Demonstrates the informal and formal usage of the toCardinal function for Thai language.
```javascript
import { toCardinal } from 'n2words/th-TH'
// Informal
toCardinal(42) // 'สี่สิบสอง'
// Formal
toCardinal(42, { formal: true }) // 'สี่สิบสอง' (formal variant)
```