UNPKG

n2words

Version:

Convert numbers to words in 70+ languages with zero dependencies. Supports BigInt, decimals, and browser/Node.js environments.

414 lines (348 loc) 12.2 kB
/** * Danish (Denmark) language converter * * CLDR: da-DK | Danish as used in Denmark * * Key features: * - Vigesimal (base-20) tens naming: halvtreds (50), treds (60), etc. * - Units-before-tens: "enogtyve" (21) = one-and-twenty * - Compound thousands: "ettusind", "firetusinde" * - "og" conjunction after hundreds and thousands * - Long scale for millions+ */ 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' // ============================================================================ // Vocabulary (module-level constants) // ============================================================================ const ONES = ['', 'et', 'to', 'tre', 'fire', 'fem', 'seks', 'syv', 'otte', 'ni'] // "en" form used in vigesimal pattern (X og Y) and before millions const ONES_VIGESIMAL = ['', 'en', 'to', 'tre', 'fire', 'fem', 'seks', 'syv', 'otte', 'ni'] const TEENS = ['ti', 'elleve', 'tolv', 'tretten', 'fjorten', 'femten', 'seksten', 'sytten', 'atten', 'nitten'] // Danish vigesimal tens (base-20 derived names) const TENS = ['', '', 'tyve', 'tredive', 'fyrre', 'halvtreds', 'treds', 'halvfjerds', 'firs', 'halvfems'] const HUNDRED = 'hundrede' const THOUSAND = 'tusind' const ZERO = 'nul' const NEGATIVE = 'minus' const DECIMAL_SEP = 'komma' // Long scale: millioner, millarder, billioner, etc. const SCALES = ['millioner', 'millarder', 'billioner', 'billarder', 'trillioner', 'trillarder', 'quadrillioner', 'quadrillarder'] // Supported magnitude ceiling (checked at the public entry points). Segments // are [units, thousands, then one per SCALES entry], so cardinals span at most // SCALES.length + 2 groups of 3 digits — they must stay below 10^30. Ordinals // and currency build on the cardinal, so they share the same ceiling. export const cardinalMax = western(SCALES.length + 1) export const ordinalMax = western(SCALES.length + 1) export const currencyMax = western(SCALES.length + 1) // ============================================================================ // Ordinal Vocabulary // ============================================================================ // Danish ordinals: 1st-2nd special, others use -te/-nde suffix // "anden/andet" for 2nd (common/neuter), we use common form /** @type {Record<number, string>} */ const ORDINAL_SPECIAL = { 1: 'første', 2: 'anden', 3: 'tredje', 4: 'fjerde', 5: 'femte', 6: 'sjette', 7: 'syvende', 8: 'ottende', 9: 'niende', 10: 'tiende', 11: 'ellevte', 12: 'tolvte', } // ============================================================================ // Currency Vocabulary (Danish Krone) // ============================================================================ const KRONE = 'krone' const KRONER = 'kroner' // plural const ORE = 'øre' // same singular and plural // ============================================================================ // Segment Building // ============================================================================ /** * Builds segment word for 0-999. * @param {number} n - Integer in range 0-999 * @returns {string} Danish words for the segment */ function buildSegment(n) { if (n === 0) return '' const ones = n % 10 const tens = Math.trunc(n / 10) % 10 const hundreds = Math.trunc(n / 100) const parts = [] // Hundreds: "ethundrede", "tohundrede" (compound, no space) if (hundreds > 0) { parts.push(ONES[hundreds] + HUNDRED) } // Tens and ones const tensOnes = n % 100 if (tensOnes === 0) { // Just hundreds } else if (tensOnes < 10) { // Single digit parts.push(ONES[ones]) } else if (tensOnes < 20) { // Teens parts.push(TEENS[ones]) } else if (ones === 0) { // Even tens parts.push(TENS[tens]) } else { // Units-before-tens: "enogtyve", "treogfyrre" parts.push(ONES_VIGESIMAL[ones] + 'og' + TENS[tens]) } // Combine with " og " between hundreds and remainder if (parts.length === 2) { return parts[0] + ' og ' + parts[1] } return parts[0] || '' } // ============================================================================ // Conversion Functions // ============================================================================ /** * Converts a non-negative integer to Danish words. * @param {bigint} n - Non-negative integer to convert * @returns {string} Danish words */ function integerToWords(n) { if (n === 0n) return ZERO // Fast path: numbers < 1000 (direct lookup) if (n < 1000n) { return buildSegment(Number(n)) } // Fast path: numbers < 1,000,000 (thousands) if (n < 1_000_000n) { const thousands = Number(n / 1000n) const remainder = Number(n % 1000n) // Compound thousands: "ettusind", "firetusind" let result = buildSegment(thousands) + THOUSAND if (remainder > 0) { // Add 'e' suffix and " og " for remainder: "firetusinde og ..." result += 'e og ' + buildSegment(remainder) } return result } // For numbers >= 1,000,000, use scale decomposition return buildLargeNumberWords(n) } /** * Builds words for numbers >= 1,000,000. * @param {bigint} n - Number >= 1,000,000 * @returns {string} Danish words */ function buildLargeNumberWords(n) { const numStr = n.toString() const len = numStr.length // Build segments of 3 digits from right to left const segments = [] const segmentSize = 3 const remainderLen = len % segmentSize let pos = 0 if (remainderLen > 0) { segments.push(Number(numStr.slice(0, remainderLen))) pos = remainderLen } while (pos < len) { segments.push(Number(numStr.slice(pos, pos + segmentSize))) pos += segmentSize } // Convert segments to words with scale tracking // Callers guard the magnitude (cardinalMax) before reaching here. // scaleIndex: 0 = units, 1 = thousands, 2 = millions, etc. const parts = [] let scaleIndex = segments.length - 1 for (let i = 0; i < segments.length; i++) { const segment = segments[i] if (segment !== 0) { const segmentWord = buildSegment(segment) if (scaleIndex === 0) { // Units segment parts.push({ word: segmentWord, type: 'units' }) } else if (scaleIndex === 1) { // Thousands - compound form parts.push({ word: segmentWord + THOUSAND, type: 'thousand' }) } else { // Millions+ - space-separated, use "en" for 1 const scaleWord = SCALES[scaleIndex - 2] let numWord = segmentWord // "et" → "en" before millions+ if (segment === 1) { numWord = 'en' } parts.push({ word: numWord + ' ' + scaleWord, type: 'million' }) } } scaleIndex-- } // Join parts with Danish rules return joinDanishParts(parts) } /** * Joins parts with Danish spacing rules. * - After thousands with remainder: "tusinde og" * - Millions are space-separated * @param {Array<{word: string, type: string}>} parts - Parts with type metadata * @returns {string} Joined string */ function joinDanishParts(parts) { if (parts.length === 0) return ZERO const tokens = [] for (let i = 0; i < parts.length; i++) { const part = parts[i] const nextPart = parts[i + 1] if (part.type === 'thousand' && nextPart && nextPart.type === 'units') { // Thousands directly followed by the units segment: compound "…tusinde og …" tokens.push(part.word + 'e og ' + nextPart.word) i++ // consumed the units part } else { tokens.push(part.word) } } // Every remaining boundary (between scale groups) is a single space. return tokens.join(' ') } /** * Converts decimal digits to Danish words. * @param {string} decimalPart - Decimal digits (without the point) * @returns {string} Danish words for decimal part */ function decimalPartToWords(decimalPart) { let result = '' // Handle leading zeros let i = 0 while (i < decimalPart.length && decimalPart[i] === '0') { if (result) result += ' ' result += ZERO i++ } // Convert remainder as a single number const remainder = decimalPart.slice(i) if (remainder) { if (result) result += ' ' result += integerToWords(BigInt(remainder)) } return result } /** * Converts a numeric value to Danish words. * @param {number | string | bigint} value - The numeric value to convert * @returns {string} The number in Danish words * @throws {TypeError} If value is not a valid numeric type * @throws {Error} If value is not a valid number format * @example * toCardinal(21) // 'enogtyve' * toCardinal(1000) // 'ettusind' * toCardinal(1000000) // 'en millioner' */ 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: toOrdinal(value) // ============================================================================ /** * Converts a non-negative integer to Danish ordinal words. * * Danish ordinals: første (1st), anden (2nd), tredje (3rd), etc. * 1-12 have special forms, others use cardinal + -de/-nde suffix. * @param {bigint} n - Positive integer to convert * @returns {string} Danish ordinal words */ function integerToOrdinal(n) { // Special forms for 1-12 if (n >= 1n && n <= 12n) { return ORDINAL_SPECIAL[Number(n)] } // For numbers > 12, add -de suffix to cardinal const cardinal = integerToWords(n) return cardinal + 'de' } /** * Converts a numeric value to Danish ordinal words. * @param {number | string | bigint} value - The numeric value to convert (positive integer) * @returns {string} The number as ordinal words * @throws {TypeError} If value is not a valid numeric type * @throws {RangeError} If value is negative, zero, or has a decimal part * @example * toOrdinal(1) // 'første' * toOrdinal(2) // 'anden' * toOrdinal(21) // 'enogtyvede' */ function toOrdinal(value) { const integerPart = parseOrdinalValue(value) checkMax(integerPart, ordinalMax) return integerToOrdinal(integerPart) } // ============================================================================ // CURRENCY: toCurrency(value) // ============================================================================ /** * Converts a numeric value to Danish currency words (Danish Krone). * * Uses krone/kroner and øre (100 øre = 1 krone). * @param {number | string | bigint} value - The currency amount to convert * @returns {string} The amount in Danish currency words * @throws {TypeError} If value is not a valid numeric type * @throws {Error} If value is not a valid number format * @example * toCurrency(1) // 'en krone' * toCurrency(42) // 'toogfyrre kroner' * toCurrency(1.50) // 'en krone og halvtreds øre' */ function toCurrency(value) { const { isNegative, dollars: kroner, cents: ore } = parseCurrencyValue(value) checkMax(kroner, currencyMax) let result = '' if (isNegative) { result = NEGATIVE + ' ' } // Kroner part - use "en" for 1 krone if (kroner > 0n || ore === 0n) { if (kroner === 1n) { result += 'en ' + KRONE } else { result += integerToWords(kroner) + ' ' + KRONER } } // Øre part if (ore > 0n) { if (kroner > 0n) { result += ' og ' } result += integerToWords(ore) + ' ' + ORE } return result } // ============================================================================ // Public API // ============================================================================ export { toCardinal, toOrdinal, toCurrency }