UNPKG

digit-to-words-nepali

Version:

A comprehensive TypeScript library for converting numbers to words in English and Nepali languages. Supports numbers up to 10^39 (Adanta Singhar), currency formatting, decimal handling, and BigInt. Zero dependencies, fully tested.

85 lines (84 loc) 3 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.digitToEnglishWords = exports.EnglishConverter = void 0; const baseConverter_1 = require("./baseConverter"); const validationUtils_1 = require("../utils/validationUtils"); const scaleMappings_1 = require("../mappings/scaleMappings"); const numberMappings_1 = require("../mappings/numberMappings"); class EnglishConverter extends baseConverter_1.BaseConverter { constructor() { super(); this.wordCache = (0, numberMappings_1.createNumberWordMap)(); this.scales = scaleMappings_1.englishScaleMappings; } convert(num, config) { this.setCustomMappings(config); if (!(0, validationUtils_1.isValidNumber)(num)) { throw new Error('Input must contain only valid digits'); } const { integer, decimal } = (0, validationUtils_1.splitNumber)(num); const words = []; // Convert integer part if (integer === 0n) { words.push(this.getWordMapping(0, 'en')); } else { this.processLargeNumber(integer, words, config); } // Handle decimal part if (config.includeDecimal && decimal) { words.push(config.isCurrency ? config.currencyDecimalSuffix : config.decimalSuffix); const decimalNum = parseInt(decimal); if (decimalNum === 0) { words.push(this.getWordMapping(0, 'en')); } else { words.push(this.getWordMapping(decimalNum, 'en')); } } // Add currency prefix if needed if (config.isCurrency) { words.unshift(config.currency); } return { words, meta: { originalNumber: num.toString(), language: 'en', isCurrency: config.isCurrency } }; } processNumber(num, words, config) { for (const scale of this.scales) { if (num >= scale.value) { const quotient = num / scale.value; num = num % scale.value; if (quotient > 0n) { this.processNumber(quotient, words, config); words.push(this.getScaleName(scale.value, 'en')); } } } if (num > 0n && num <= 99n) { words.push(this.getWordMapping(Number(num), 'en')); } } } exports.EnglishConverter = EnglishConverter; const digitToEnglishWords = (num, config = {}) => { const converter = new EnglishConverter(); const result = converter.convert(num, { lang: 'en', isCurrency: false, includeDecimal: true, currency: 'Dollars', decimalSuffix: 'point', currencyDecimalSuffix: 'cents', units: {}, scales: {}, ...config }); return result.words.join(' ').trim(); }; exports.digitToEnglishWords = digitToEnglishWords;