UNPKG

num2txt

Version:

Converts number to Vietnamese or English text with customized output.

72 lines (71 loc) 3.58 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.num2txt = exports.TRIPLET_MAX_LENGTH = void 0; const configs_1 = require("./configs"); const text_1 = require("./helpers/text"); const tripletToEng_1 = require("./helpers/tripletToEng"); const tripletToVie_1 = require("./helpers/tripletToVie"); exports.TRIPLET_MAX_LENGTH = 7; const suffixes = ['', 'nghìn ', 'triệu ', 'tỷ ', 'nghìn tỷ ', 'triệu tỷ ', 'tỷ tỷ ']; const suffixesEng = ['', 'thousand ', 'million ', 'billion ', 'trillion ', 'quadrillion ', 'quintillion ']; function num2txt(value, options = configs_1.defaultOptions) { const customOptions = Object.assign(Object.assign({}, configs_1.defaultOptions), options); const triplets = [0, 0, 0, 0, 0, 0, 0]; let isMoreThanAThousand; let index = 0; let outputString = ''; try { let number = typeof value === 'string' ? parseFloat(value) : value; if (isNaN(number)) { throw new Error('Invalid input'); } if (number < 0) { outputString += (customOptions === null || customOptions === void 0 ? void 0 : customOptions.lang) === 'en' ? 'negative ' : 'âm '; number = Math.abs(number); } isMoreThanAThousand = number >= 1000; if (number == 0) { outputString += (customOptions === null || customOptions === void 0 ? void 0 : customOptions.lang) === 'en' ? 'zero ' : 'không '; } while (number >= 1) { triplets[index++] = number % 1000; number = Math.floor(number / 1000); } triplets.reverse(); suffixes.reverse(); suffixesEng.reverse(); for (const [tIndex, triplet] of triplets.entries()) { if ((customOptions === null || customOptions === void 0 ? void 0 : customOptions.lang) === 'en') { outputString += (0, tripletToEng_1.tripletToEng)(triplet, tIndex, isMoreThanAThousand); if (triplet != 0) { outputString += suffixesEng[tIndex]; if (options.commaSeparator && tIndex < exports.TRIPLET_MAX_LENGTH - 1) { outputString = outputString.slice(0, -1) + ', '; } } } else { outputString += (0, tripletToVie_1.tripletToVie)(triplet, Math.abs(exports.TRIPLET_MAX_LENGTH - tIndex - index)); if (triplet != 0) { outputString += suffixes[tIndex]; if (options.commaSeparator && tIndex < exports.TRIPLET_MAX_LENGTH - 1) { outputString = outputString.slice(0, -1) + ', '; } } } } suffixes.reverse(); suffixesEng.reverse(); if (customOptions === null || customOptions === void 0 ? void 0 : customOptions.currencyUnit) { outputString += customOptions === null || customOptions === void 0 ? void 0 : customOptions.currencyUnit; if ((customOptions === null || customOptions === void 0 ? void 0 : customOptions.lang) === 'en' && (typeof value === 'string' ? parseFloat(value) : value) > 1) { outputString += 's'; } } return (0, text_1.transformText)(outputString.trim(), customOptions === null || customOptions === void 0 ? void 0 : customOptions.textTransform); } catch (error) { return error.message; } } exports.num2txt = num2txt;