UNPKG

currency-in-words

Version:

A light-weight, fast and efficient lib that converts currency or any numbers to corresponding words

66 lines 2.62 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.convert = void 0; var utils_1 = require("./utils"); var globalConfig_1 = require("./lib/globalConfig"); /** * @TODO Fix: converted and translated(literally) are used interchangabily. */ /** * * @param value value to be converted, this can typically contain integer and fractional part, eg: 99.99 * @param param1 <object> { format: string, lang: string } * @returns NaN for invalid input * @returns translated value * * @throws rangeException */ function convert(value, _a) { var _b = _a === void 0 ? { format: (0, globalConfig_1.getGlobalConfig)().format, lang: (0, globalConfig_1.getGlobalConfig)().lang } : _a, format = _b.format, lang = _b.lang; /** Update the globalConfig */ (0, globalConfig_1.setGlobalConfig)({ lang: lang, format: format }); /** * Safe guard against invalid inputs * this rejects strings if contained invalid input * * reject invalid strings; returns 'NaN' */ if (!value || !value.match(/^\d*(\.\d+)?$/)) return 'NaN'; /** * Integer and fraction parts are processed seperately, though the same logic is reused * * zeroCorrected: this is to sanitize all the preceding zeores * eg: 001 to 1, 099 to 99 * * twoDecimalPlaces: the factional part is corrected to two decimal places and anything lesser than .10 is rejected * eg: .18 to .18 * .09 to '' */ var _c = value.split('.'), integer = _c[0], fraction = _c[1]; var zeroCorrected = "".concat(parseInt(integer, 10)); var twoDecimalPlaces = parseInt(fraction, 10) >= 10 ? "".concat(fraction.substring(0, 2)) : ""; /** * This handles place values upto 15 for both indian and international systems, and anything beyond that is thrown with a range error */ if (zeroCorrected.length > 15) throw new RangeError('Number exceeds the range'); /** * Handles when passed in just fractional parts * eg: 0.99, 0.77 etc * * If the sanitized input is still 0, returns 'zero' * eg: '00', '000' */ if (parseInt(fraction, 10) >= 10 && zeroCorrected === '0') return "zero.".concat((0, utils_1.handleTens)(twoDecimalPlaces)); if (zeroCorrected === '0') return 'zero'; // International format if (format === 'intl') return (0, utils_1.convertIntl)(zeroCorrected, fraction, twoDecimalPlaces); // Indian format return (0, utils_1.convertInd)(zeroCorrected, fraction, twoDecimalPlaces); } exports.convert = convert; //# sourceMappingURL=index.js.map