@sebgroup/frontend-tools
Version:
A set of frontend tools
54 lines (50 loc) • 1.9 kB
JavaScript
;
Object.defineProperty(exports, '__esModule', { value: true });
/**
* 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 "";
}
}
exports.toCurrency = toCurrency;
//# sourceMappingURL=toCurrency.js.map