n2words
Version:
Convert numbers to words in 70+ languages with zero dependencies. Supports BigInt, decimals, and browser/Node.js environments.
417 lines (346 loc) • 11.7 kB
JavaScript
/**
* Philippine English language converter
*
* CLDR: en-PH | English as used in the Philippines
*
* Exports:
* - toCardinal(value) - Cardinal numbers: 42 → "forty-two"
* - toOrdinal(value) - Ordinal numbers: 42 → "forty-second"
* - toCurrency(value, options?) - Currency: 42.50 → "forty-two pesos and fifty centavos"
*
* Philippine English conventions:
* - Follows British English style
* - "and" after hundreds: "one hundred and twenty-three"
* - "and" before final segment: "one million and one"
* - Hyphenated tens-ones: "twenty-one", "forty-two"
* - Western numbering system (short scale: billion = 10^9)
* - Currency: Philippine Peso (PHP) - peso/pesos, centavo/centavos
*/
import { parseCardinalValue } from './utils/parse-cardinal.js'
import { parseCurrencyValue } from './utils/parse-currency.js'
import { parseOrdinalValue } from './utils/parse-ordinal.js'
import { checkMax } from './utils/check-max.js'
import { western } from './utils/scale.js'
import { resolveOptions } from './utils/resolve-options.js'
// ============================================================================
// Vocabulary (module-level constants)
// ============================================================================
const ONES = ['', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
const TEENS = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
const TENS = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
const SCALES = [
'thousand', 'million', 'billion', 'trillion', 'quadrillion',
'quintillion', 'sextillion', 'septillion', 'octillion', 'nonillion',
'decillion', 'undecillion', 'duodecillion', 'tredecillion', 'quattuordecillion',
'quindecillion', 'sexdecillion', 'septendecillion', 'octodecillion', 'novemdecillion',
'vigintillion',
]
export const cardinalMax = western(SCALES.length)
export const ordinalMax = western(SCALES.length)
export const currencyMax = western(SCALES.length)
const HUNDRED = 'hundred'
const ZERO = 'zero'
const NEGATIVE = 'minus'
const DECIMAL_SEP = 'point'
// Ordinal vocabulary
const ORDINAL_ONES = ['', 'first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth']
const ORDINAL_TEENS = ['tenth', 'eleventh', 'twelfth', 'thirteenth', 'fourteenth', 'fifteenth', 'sixteenth', 'seventeenth', 'eighteenth', 'nineteenth']
const ORDINAL_TENS = ['', '', 'twentieth', 'thirtieth', 'fortieth', 'fiftieth', 'sixtieth', 'seventieth', 'eightieth', 'ninetieth']
// Currency vocabulary (Philippine Peso)
const PESO = 'peso'
const PESOS = 'pesos'
const CENTAVO = 'centavo'
const CENTAVOS = 'centavos'
// ============================================================================
// Segment Building
// ============================================================================
const segmentResult = { word: '', hasHundred: false }
/**
* @param {number} n The 0-999 segment value to convert.
* @returns {{word: string, hasHundred: boolean}} The segment words and whether it includes a hundreds place.
*/
function buildSegment(n) {
if (n === 0) {
segmentResult.word = ''
segmentResult.hasHundred = false
return segmentResult
}
const ones = n % 10
const tens = Math.trunc(n / 10) % 10
const hundreds = Math.trunc(n / 100)
let tensOnes = ''
if (tens === 1) {
tensOnes = TEENS[ones]
}
else if (tens >= 2) {
tensOnes = ones > 0 ? TENS[tens] + '-' + ONES[ones] : TENS[tens]
}
else if (ones > 0) {
tensOnes = ONES[ones]
}
if (hundreds > 0) {
if (tensOnes) {
segmentResult.word = ONES[hundreds] + ' ' + HUNDRED + ' and ' + tensOnes
}
else {
segmentResult.word = ONES[hundreds] + ' ' + HUNDRED
}
segmentResult.hasHundred = true
}
else {
segmentResult.word = tensOnes
segmentResult.hasHundred = false
}
return segmentResult
}
// ============================================================================
// Conversion Functions
// ============================================================================
/**
* @param {bigint} n The non-negative integer to convert.
* @returns {string} The integer in English words.
*/
function integerToWords(n) {
if (n === 0n) return ZERO
if (n < 1000n) {
return buildSegment(Number(n)).word
}
if (n < 1_000_000n) {
const thousands = Number(n / 1000n)
const remainder = Number(n % 1000n)
const { word: thousandsWord } = buildSegment(thousands)
let result = thousandsWord + ' ' + SCALES[0]
if (remainder > 0) {
const { word: remainderWord, hasHundred } = buildSegment(remainder)
result += hasHundred ? ' ' + remainderWord : ' and ' + remainderWord
}
return result
}
return buildLargeNumberWords(n)
}
/**
* @param {bigint} n The integer of one million or greater to convert.
* @returns {string} The integer in English words.
*/
function buildLargeNumberWords(n) {
const segments = []
let temp = n
while (temp > 0n) {
segments.push(Number(temp % 1000n))
temp = temp / 1000n
}
let firstNonZeroIdx = -1
for (let i = 0; i < segments.length; i++) {
if (segments[i] !== 0) {
firstNonZeroIdx = i
break
}
}
let result = ''
let prevWasScale = false
for (let i = segments.length - 1; i >= 0; i--) {
const segment = segments[i]
if (segment === 0) continue
const { word, hasHundred } = buildSegment(segment)
const isLastSegment = (i === firstNonZeroIdx)
if (result && isLastSegment && prevWasScale && !hasHundred) {
result += ' and'
}
if (result) result += ' '
result += word
if (i > 0) {
result += ' ' + SCALES[i - 1]
prevWasScale = true
}
else {
prevWasScale = false
}
}
return result
}
/**
* @param {string} decimalPart The fractional digits to convert.
* @returns {string} The decimal digits in English words.
*/
function decimalPartToWords(decimalPart) {
let result = ''
let i = 0
while (i < decimalPart.length && decimalPart[i] === '0') {
if (result) result += ' '
result += ZERO
i++
}
const remainder = decimalPart.slice(i)
if (remainder) {
if (result) result += ' '
result += integerToWords(BigInt(remainder))
}
return result
}
/**
* Converts a numeric value to Philippine English words.
* @param {number | string | bigint} value - The numeric value to convert
* @returns {string} The number in English words
* @throws {TypeError} If value is not a valid numeric type
* @throws {Error} If value is not a valid number format
*/
function toCardinal(value) {
const { isNegative, integerPart, decimalPart } = parseCardinalValue(value)
// Both the integer part and the decimal's significant digits are spelled via
// the scale builder, so both must clear the ceiling.
checkMax(integerPart, cardinalMax, decimalPart)
let result = ''
if (isNegative) {
result = NEGATIVE + ' '
}
result += integerToWords(integerPart)
if (decimalPart) {
result += ' ' + DECIMAL_SEP + ' ' + decimalPartToWords(decimalPart)
}
return result
}
// ============================================================================
// ORDINAL
// ============================================================================
/**
* @param {number} n The 0-999 segment value to convert.
* @returns {string} The segment as ordinal words.
*/
function buildOrdinalSegment(n) {
const ones = n % 10
const tens = Math.trunc(n / 10) % 10
const hundreds = Math.trunc(n / 100)
let tensOnesOrdinal = ''
if (tens === 1) {
tensOnesOrdinal = ORDINAL_TEENS[ones]
}
else if (tens >= 2) {
if (ones > 0) {
tensOnesOrdinal = TENS[tens] + '-' + ORDINAL_ONES[ones]
}
else {
tensOnesOrdinal = ORDINAL_TENS[tens]
}
}
else if (ones > 0) {
tensOnesOrdinal = ORDINAL_ONES[ones]
}
if (hundreds > 0) {
if (tensOnesOrdinal) {
return ONES[hundreds] + ' ' + HUNDRED + ' ' + tensOnesOrdinal
}
else {
return ONES[hundreds] + ' hundredth'
}
}
return tensOnesOrdinal
}
/**
* @param {bigint} n The positive integer to convert.
* @returns {string} The integer as ordinal words.
*/
function integerToOrdinal(n) {
if (n < 1000n) {
return buildOrdinalSegment(Number(n))
}
if (n < 1_000_000n) {
const thousands = Number(n / 1000n)
const remainder = Number(n % 1000n)
if (remainder === 0) {
return buildSegment(thousands).word + ' ' + SCALES[0] + 'th'
}
const { word: thousandsWord } = buildSegment(thousands)
return thousandsWord + ' ' + SCALES[0] + ' ' + buildOrdinalSegment(remainder)
}
return buildLargeOrdinal(n)
}
/**
* @param {bigint} n The integer of one million or greater to convert.
* @returns {string} The integer as ordinal words.
*/
function buildLargeOrdinal(n) {
const segments = []
let temp = n
while (temp > 0n) {
segments.push(Number(temp % 1000n))
temp = temp / 1000n
}
let lowestNonZeroIdx = 0
for (let i = 0; i < segments.length; i++) {
if (segments[i] !== 0) {
lowestNonZeroIdx = i
break
}
}
let result = ''
for (let i = segments.length - 1; i >= 0; i--) {
const segment = segments[i]
if (segment === 0) continue
const isLowestSegment = (i === lowestNonZeroIdx)
if (result) result += ' '
if (isLowestSegment) {
if (i === 0) {
result += buildOrdinalSegment(segment)
}
else {
result += buildSegment(segment).word + ' ' + SCALES[i - 1] + 'th'
}
}
else {
result += buildSegment(segment).word
if (i > 0) {
result += ' ' + SCALES[i - 1]
}
}
}
return result
}
/**
* Converts a numeric value to Philippine English ordinal words.
* @param {number | string | bigint} value - The numeric value to convert (must be a positive integer)
* @returns {string} The number as ordinal words (e.g., "first", "forty-second")
* @throws {TypeError} If value is not a valid numeric type
* @throws {RangeError} If value is negative, zero, or has a decimal part
*/
function toOrdinal(value) {
const integerPart = parseOrdinalValue(value)
checkMax(integerPart, ordinalMax)
return integerToOrdinal(integerPart)
}
// ============================================================================
// CURRENCY
// ============================================================================
/**
* @typedef {object} CurrencyOptions
* @property {boolean} [and] - Use "and" between pesos and centavos
*/
/** @type {Required<CurrencyOptions>} */
export const currencyDefaults = { and: true }
/**
* Converts a numeric value to Philippine English currency words.
* @param {number | string | bigint} value - The numeric value to convert
* @param {CurrencyOptions} [options] - Optional configuration
* @returns {string} The amount in Philippine English currency words
* @throws {TypeError} If value is not a valid numeric type
* @throws {Error} If value is not a valid number format
*/
function toCurrency(value, options) {
const { isNegative, dollars: pesos, cents: centavos } = parseCurrencyValue(value)
checkMax(pesos, currencyMax)
const { and: useAnd } = resolveOptions(options, currencyDefaults)
let result = ''
if (isNegative) result = NEGATIVE + ' '
if (pesos > 0n || centavos === 0n) {
result += integerToWords(pesos)
result += ' ' + (pesos === 1n ? PESO : PESOS)
}
if (centavos > 0n) {
if (pesos > 0n) {
result += useAnd ? ' and ' : ' '
}
result += integerToWords(centavos)
result += ' ' + (centavos === 1n ? CENTAVO : CENTAVOS)
}
return result
}
export { toCardinal, toOrdinal, toCurrency }