UNPKG

@sebgroup/frontend-tools

Version:
50 lines (48 loc) 1.81 kB
/** * Formats a number or a string number to a currency format * @param {number} value raw number value * @param {ToCurrencyOptions} options You can control the sperator, radix, decimals visibility and number of decimal places using these options * @returns {string} The formatted currency string */ function toCurrency(value, options = {}) { let amount = "0"; const format = (val) => { let num; let cents; if (val - Math.floor(val) === 0) { num = val; } else { num = Math.floor(val); if ((options === null || options === void 0 ? void 0 : options.showDecimals) !== false) { cents = Number((val - Math.floor(val)) .toFixed((options === null || options === void 0 ? void 0 : options.numOfDecimals) || 2) .replace("0.", "")); } } const list = String(num).split(""); const newList = []; list.map((item, index) => { if ((list.length - (index + 1) || 1) % 3 === 0) { newList.push(item); newList.push((options === null || options === void 0 ? void 0 : options.separator) || ","); } else { newList.push(item); } }); amount = newList.join(""); return (amount + (cents ? `${(options === null || options === void 0 ? void 0 : options.decimalSymbol) || "."}${cents}` : "")); }; if (typeof value === "number") { return format(value); } else if (typeof value === "string" && !isNaN(Number(value))) { return format(Number(value)); } else { return ""; } } export { toCurrency }; //# sourceMappingURL=toCurrency.js.map